The web container maintains the life cycle of a servlet instance.
Stages of the Servlet Life Cycle:
Syntax
public void init(ServletConfig config) throws ServletException {
// Initialization code...
}
Syntax
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
Syntax
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
Syntax
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
Syntax
public void destroy() {
// Finalization code...
}
ServletContext is a configuration Object which is created when web application is started. It contains different initialization parameter that can be configured in web.xml.
ServletContext Interface Methods
1. public String getInitParameter(String name): Returns the parameter value for the specified parameter name.
2. public Enumeration getInitParameterNames(): Returns the names of the context’s initialization parameters.
3. public void setAttribute(String name,Object object): sets the given object in the application scope.
4. public Object getAttribute(String name): Returns the attribute for the specified name.
5. public Enumeration getInitParameterNames(): Returns the names of the context’s initialization parameters as an Enumeration of String objects.
6. public void removeAttribute(String name): Removes the attribute with the given name from the servlet context.
Example: DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter pwriter=response.getWriter();
// ServletContext object creation
ServletContext scontext=getServletContext();
// fetching values of initialization parameters and printing it
String userName=scontext.getInitParameter("uname");
pwriter.println("User name is="+userName);
String userEmail=scontext.getInitParameter("email");
pwriter.println("Email Id is="+userEmail);
pwriter.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>UserDetails</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>uname</param-name>
<param-value>Pradeep Kumar</param-value>
</context-param>
<context-param>
<param-name>email</param-name>
<param-value>pradeep.vwa@gmail.com</param-value>
</context-param>
<servlet-mapping>
<servlet-name>UserDetails</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
A servlet is an interface whose implementation extends the functionality of a server. A servlet interacts with clients through a request-response principle. Although servlets can handle any request, they are commonly used to expand web servers.
Most of the classes and interfaces required to create servlets are contained in javax.servlet
and packages javax.servlet.http
.
Basic servlet methods
public void init(ServletConfig config) throws ServletException
starts immediately after loading the servlet into memory;public ServletConfig getServletConfig()
returns a reference to an object that provides access to servlet configuration information;public String getServletInfo()
returns a string containing information about the servlet, for example: author and version of the servlet;public void service(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException
called to process each request;public void destroy()
performed before unloading the servlet from memory.A servlet container is a program that is a server that provides system support for servlets and ensures their life cycle in accordance with the rules defined in the specifications. It can work as a full-fledged stand-alone web server, be a page provider for another web server, or integrate into a Java EE application server.
The servlet container provides data exchange between the servlet and clients, takes on the execution of functions such as creating a software environment for a functioning servlet, identifying and authorizing clients, and organizing a session for each of them.
The most famous servlet container implementations are:
The servlet container manages the four phases of the servlet life cycle:
init()
method. This is where the servlet class is converted from a regular class to a servlet.service()
by passing a reference to the object’s responses and request.destroy()
method.Thus, the servlet is created the first time it is accessed and lives throughout the entire application run time (unlike the class objects that are destroyed by the garbage collector after they are no longer used) and the entire servlet life cycle can be described as a sequence of method calls:
public void init(ServletConfig config)
- Used by the container to initialize the servlet. Called once during the servlet’s lifetime.public void service(ServletRequest request, ServletResponse response)
- called for each request. The method cannot be called before the init()method is executed .public void destroy()
- called to destroy the servlet (once during the life of the servlet).To create a servlet ExampleServlet
, you must describe it in the deployment descriptor:
<servlet-mapping>
<servlet-name> ExampleServlet </servlet-name>
<url-pattern> / example </url-pattern>
</servlet-mapping>
<servlet>
<servlet-name> ExampleServlet </servlet-name>
<servlet-class> xyz.company.ExampleServlet </servlet-class>
<init-param>
<param-name> config </param-name>
<param-value> default </param-value>
</init-param>
</servlet>
Then create a class xyz.company.ExampleServlet
by inheriting from HttpServlet
and implement the logic of its work in the method service()
/ methods doGet()
/ doPost()
.
To call a servlet from the same application, you must use the inter-servlet communication mechanisms through method calls RequestDispatcher()
:
forward()
- passes the execution of the request to another servlet;include()
- provides the ability to include the result of another servlet in the returned response.If you need to call a servlet belonging to another application, then you RequestDispatcher
will not be able to use it, because it is defined only for the current application. For such purposes, you must use the method ServletResponse- sendRedirect()
which is provided with the full URL of another servlet. You can use to transfer data between servlets cookies.
The RequestDispatcher
interface is used to transfer the request to another resource, while it is possible to add data received from this resource to the servlet’s own response. This interface is also used for internal communication between servlets in the same context.
Two methods are implemented in the interface:
void forward(ServletRequest var1, ServletResponse var2)
- transfers the request from the servlet to another resource (servlet, JSP or HTML file) on the server.void include(ServletRequest var1, ServletResponse var2)
- includes the content of the resource (servlet, JSP or HTML page) in the response.Access to the interface can be obtained using the interface method ServletContext
- RequestDispatcher getRequestDispatcher(String path)
, where the path starting with /
is interpreted relative to the current root path of the context.
forward()
sendRedirect()
Servlet attributes are used for internal servlet communication.
The web application has the ability to work with attributes using the methods setAttribute()
, getAttribute()
, removeAttribute()
, getAttributeNames()
, who provided interfaces ServletRequest, HttpSessionand ServletContext(for the scope request, the session, context The respectively).
The real path to the servlet location on the server can be obtained from the object
ServletContext: getServletContext().getRealPath(request.getServletPath())
.
Information about the server can be obtained from the object ServletContext:
getServletContext().getServerInfo()
.
Client IP address can be obtained by calling request.getRemoteAddr()
.
Custom handlers can ServletRequest
also ServletResponse
be implemented by adding new or overriding existing methods for wrapper classes ServletRequestWrapper( HttpServletRequestWrapper)
and ServletResponseWrapper( HttpServletRequestWrapper)
.
An abstract class GenericServletis an implementation of the interface independent of the protocol used Servlet, and an abstract class, HttpServletin turn, extends GenericServletfor the HTTP protocol.
doGet()
- for processing HTTP requests GET;doPost()
- for processing HTTP requests POST;doPut()
- for processing HTTP requests PUT;doDelete()
- for processing HTTP requests DELETE;doHead()
- for processing HTTP requests HEAD;doOptions()
- for processing HTTP requests OPTIONS;doTrace()
- for processing HTTP requests TRACE.An HTTP method is called immutable if it always returns the same result on the same request. HTTP methods GET
, PUT
, DELETE
, HEAD
and OPTIONS
are immutable, so it is necessary to implement an application so that these methods return the same results consistently. Variable methods include a method POST
that is used to implement something that changes with each request.
For example, to access a static HTML page, a method is used GET
, because it always returns the same result. If you need to save any information, for example in a database, you need to use the POST
method.
There are several ways to provide a unique session identifier:
Cookies (“cookies”) - a small piece of data sent by a web server and stored on the user’s device. Each time you try to open a site page, the web client sends cookies corresponding to this site to the web server as part of the HTTP request. It is used to save data on the user side and in practice it is usually used to:
Servlet API provides support for cookies through the class javax.servlet.http.Cookie
:
HttpServletRequest.getCookies()
. There are no methods for adding cookies to HttpServletRequest
.HttpServletResponse.addCookie(Cookie c)
. There is no method to receive cookies HttpServletResponse
.URL Rewriting - special rewriting (recoding) of the original URL. This mechanism can be used to control the session in servlets when cookies are disabled.
HttpServletResponse.encodeURL()
provides a way to convert a URL to HTML hyperlink with the conversion of special characters and spaces, as well as adding session id to the URL. This behavior is similar java.net.URLEncoder.encode()
, but with the addition of an additional parameter jsessionid
at the end of the URL.
The method HttpServletResponse.encodeRedirectURL()
translates the URL for later use in the method sendRedirect()
.
Thus for HTML hyperlinks when URL rewriting is necessary to use encodeURL()
, and for the URL when redirecting - encodeRedirectUrl()
.
To be sure that the object will be notified about the termination of the session, you need to implement the interface javax.servlet.http.HttpSessionBindingListener
. Two methods of this interface: valueBound()
and valueUnbound()
are used when adding an object as an attribute to a session and when destroying a session, respectively.
Servlet filters are used to intercept all requests between the servlet container and the servlet. Therefore, it is logical to use the appropriate filter to check the necessary information (for example, the validity of the session) in the request.
To provide transport layer security, you must configure SSL support for the container servlet. How to do this depends on the particular implementation of the servlet container.
The servlet specification defines four types of authentication:
BASIC
: When accessing private resources, a window appears that asks you to enter authentication information.FORM
: The native html form is used:DIGEST
: Digital authentication with encryption.CLIENT-CERT
: Authentication with a client certificate.
```xml#### Q. What is a deployment descriptor?
A deployment descriptor is an artifact configuration file that will be deployed to a servlet container. In the Java Platform specification, Enterprise Edition, the deployment descriptor describes how a component, module, or application (such as a web or enterprise application) should be deployed.
This configuration file specifies the deployment settings for a module or application with specific settings, security settings, and describes specific configuration requirements. The deployment descriptor file syntax is XML.
```xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi : schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name> Display name. </display-name>
<description> Description text. </description>
<servlet>
<servlet-name> ExampleServlet </servlet-name>
<servlet-class> xyz.company.ExampleServlet </servlet-class>
<load-on-startup> 1 </load-on-startup>
<init-param>
<param-name> configuration </param-name>
<param-value> default </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name> ExampleServlet </servlet-name>
<url-pattern> / example </url-pattern>
</servlet-mapping>
<servlet>
<servlet-name> ExampleJSP </servlet-name>
<jsp-file> /sample/Example.jsp </jsp-file>
</servlet>
<context-param>
<param-name> myParam </param-name>
<param-value> the value </param-value>
</context-param>
</web-app>
For web applications, the deployment descriptor must be named web.xml
and located in the directory WEB-INF
at the root of the web application. This file is the standard deployment descriptor defined in the specification. There are also other types of descriptors, such as a deployment descriptor file sun-web.xml
that contains Sun GlassFish Enterprise Server- specific deployment information for that particular application server or a file application.xml
in the J2EEMETA-INF
application directory.
The Listener (listener) acts as a trigger, performing certain actions when an event occurs in the servlet’s life cycle.
Listeners divided by scope:
ServletRequestListener
used to catch the moment of creation and destruction of the request;ServletRequestAttributeListener
used to listen for events occurring with request attributes.ServletContextListener
allows you to catch the moment when the context is initialized or destroyed;ServletContextAttributeListener
used to listen for events occurring with attributes in context.HttpSessionListener
allows you to catch the moment of creation and destruction of the session;HttpSessionAttributeListener
used when listening to events occurring with attributes in the session;HttpSessionActivationListener
used if session migration occurs between different JVMs in distributed applications;HttpSessionBindingListener
It is also used to listen for events occurring with attributes in the session. The difference between HttpSessionAttributeListener
and HttpSessionBindingListenerlisteners
: the first is declared in web.xml
; an instance of the class is created automatically by the container in the singular and applies to all sessions; second: an instance of the class must be created and assigned to a certain session “manually”, the number of instances is also independently regulated.Connecting listeners:
<web-app>
...
<listener>
<listener-class> xyz.company.ExampleListener </listener-class>
</listener>
...
</web-app>
HttpSessionBindingListener
It is connected as an attribute directly to the session, i.e. to connect it you need to:
setAttribute(String, Object)
.Filters should be used if it is necessary to process incoming or outgoing data (for example: for authentication, format conversion, compression, encryption, etc.), if it is necessary to respond to events, it is better to use listeners.
A servlet container typically loads a servlet at the first request of a client.
If you need to load a servlet right at the start of the application (for example, if the servlet has been loading for a long time), you should use an element
If the integer value of this parameter is negative, then the servlet will be loaded when the client requests. Otherwise, it will load at the start of the application, and the smaller the number, the earlier it will be in the download queue.
<servlet>
<servlet-name> ExampleServlet </servlet-name>
<servlet-class> xyz.company.ExampleServlet </servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
When the application throws an exception, the servlet container processes it and creates an HTML response. This is similar to what happens with error codes like 404, 403, etc.
In addition to this, it is possible to write your own servlets to handle exceptions and errors with their indication in the deployment descriptor:
<error-page>
<error-code> 404 </error-code>
<location> / AppExceptionHandler </location>
</error-page>
<error-page>
<exception-type> javax.servlet.ServletException </exception-type>
<location> / AppExceptionHandler </location>
</error-page>
The main task of these servlets is to handle the error / exception and generate an understandable response to the user. For example, provide a link to the main page or a description of the error.
A servlet filter is reusable Java code that converts the contents of HTTP requests, HTTP responses, and the information contained in HTML headers. The servlet filter pre-processes the request before it gets to the servlet, and / or subsequently processes the response coming from the servlet.
Servlet filters can:
A servlet filter can be configured to work with a single servlet or a group of servlets. The basis for the formation of filters is an interface javax.servlet.Filterthat implements three methods:
void init(FilterConfig config) throws ServletException;
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
void destroy();
Signature:
void sendRedirect(String url)
Signature:
forward(ServletRequest request, ServletResponse response)
Forward() | SendRediret() |
---|---|
The forward() method is executed in the server side. | The sendRedirect() method is executed in the client side. |
The request is transfer to other resource within same server. | The request is transfer to other resource to different server. |
It does not depend on the client’s request protocol since the forward ( ) method is provided by the servlet container. | The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients. |
The request is shared by the target resource. | New request is created for the destination resource. |
Only one call is consumed in this method. | Two request and response calls are consumed. |
It can be used within server. | It can be used within and outside the server. |
The forward() method is faster than sendRedirect() method. | The sendRedirect() method is slower because when new request is created old request object is lost. |
It is declared in RequestDispatcher interface. | It is declared in HttpServletResponse. |
Signature: forward(ServletRequest request, ServletResponse response) | Signature: void sendRedirect(String url) |
Example: sendRedirect() method
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
res.sendRedirect("https://www.java.com/en/");
out.close();
}
}
Example: forward() method
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Simple" method="get">
Name: <input type="text" name="username">
password: <input type="password" name="password"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
SimpleServlet.java
package javaexample.net.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String str = request.getParameter("username");
String st = request.getParameter("password");
if (st.equals("javaexample")) {
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);
} else {
out.print("Sorry username or password incorrect!");
RequestDispatcher rd = request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}