Servlet is used for development of dynamic web application in Java. Servlet is also used to describe components which are developed using servlet API. As a component Servlet is a class that is instantiated and managed by the Web Server for generating dynamic HTML.
Before Servlet dynamic Web Application used to be build using CGI.
CGI is a protocol that defines the mode of communication between a Web Server and a CGI scrip. A CGI script is a program written in C/C++/Perl that uses CGI to communicate with Web Server.
CGI based Web Application had following 2 problems –
1) CGI scripts were platform dependent.
2) Execution of CGI script was process based i.e. for each request a new process was initialized by the Web Server.
Process based execution creates lot of overhead and limits the scalability of the application.
Servlet as technology solved both these problems by providing a thread based of request processing.
javax.servlet and its sub-packages contains interfaces and helper classes which facilitates development of Servlet.
At the core of Servlet API we have –
javax.servlet.Servlet – is an interface of Servlet API that defines the life cycle method of a Servlet. Implementation of this interface need to be provided by each Servlet.
Life Cycle Method of each Servlet –
1) init() – This method is invoked only once after a Servlet object is created. It is used by the Web Server to provide the reference of an object of type javax.Servlet.ServletConfig to the Servlet.
It can be used by the application developer to perform initialization.
public void init(Servletconfig config);
ServletConfig is an interface of Servlet API implementation of which is provided by Web Server vendors.
2) service() – This method is invoked by the server each time a request for the servlet is received. It is used by application developers to process request.
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException. In this method Web Server provides the reference of objects of type ServletRequest and ServletResponse.
These are interfaces of Servlet API implementation of these are provided by Web Server vendor.
3) destroy() – is invoked only once just before a servlet is unloaded by the server. It can be used by the application developer to perform clean up operation.
public void destroy()
Servlet interface provides 2 non life cycle methods –
1) getServletConfig() – it is used by the application developer to obtain the reference of ServletConfig object.
public ServletConfig getServletConfig()
2) getServletInfo() – This method can be used by application developer to describe their Servlet.
public String getServletInfo();
App Developer Client WebServer ServletConfig ServletRequest Servlet Response Thread Servlet
1.0 – Client sends initial request for a Servlet to WebServer
1.1 – Servlet object is created by the Web Server
1.2 – ServletConfig object is created by WebServer for Servlet.
1.3 – Reference of ServletConfig is passed in init() method.
1.4 – ServletRequest object is created by WebServer and populated with request data.
1.5 – ServletResponse object is created by WebServer.
1.6 – Request processing thread is started by WebServer.
1.7 – service() method is invoked by thread.
2.0 – Subsequent request for the Servlet is send from client
2.1 – same as 1.4
2.2 – same as 1.5
2.3 – same as 1.6
2.4 – service method is invoked by thread
3.0 – undeploy application
3.1 – destroy() method is invoked by WebServer
In order to define a Servlet implementation of Servlet interface need to be provided. It can be done in 2 ways directly or indirectly
Servlet <—– YourServlet(Direct Implementation)
public class YourServlet implements Servlet
{
definition of all the methods of Servlet interface need to be provided.
}
Servlet API provides an abstract class named GenericServlet which implements Servlet interface and can be used as a base class for a Servlet.
Servlet <—- GenericServlet <—— YourServlet
public class YourServlet extends GenericServlet
{
define service() method
}
Implementation of Servlet interface in GenericServlet is protocol neutral. In a web application Http protocol is used for communication between web server and clients. Http protocol supports multiple types of requests such as – Get, Post, Put, put, head, delete, trace, option, connect.
javax.servlet.http.HttpServlet class extends GenericServlet and defines methods which are used to handle http requests. Most commonly used among these methods are doGet() and doPost() which are used to process Http Get and Post request respectively.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
HttpServletRequest extends ServletRequest
HttpServletResponse extends ServletResponse
Servlet <— GenericServlet <—- HttpServlet <—– YourServlet (Http specific methods)
public class YourServlet extends HttpServlet
{
override doGet/doPost methods
}
//implementation of HttpServlet
public class HttpServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
{
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
service(req,res);
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
type of request is checked and doGet(), doPost() method are invoked.
}
public void doGet()
{
// blank implementation
}
public void doPost()
{
// blank implementation
}
}
Client WebServer Servlet GenericServlet HttpServlet YourServlet
1.0 – Client send a get request for a servlet to WebServer
1.1 – Servlet object is created by WebServer
1.2 – init() method is invoked by WebServer
1.3 – init() of GenericServlet is executed
1.4 – service(request, response) of Servlet is invoked by WebServer
1.5 – Servlet calls service(ServletRequest, ServletResponse) method of HttpServlet class is executed.
1.6 – In HttpServlet Class from public service() protected service() method is invoked.
1.7 – service(HttpServletRequest, HttpServletResponse) of HttpServlet is executed.
1.8 – Type of request is checked and doGet() of YourServlet is invoked
helloServlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
String name = request.getParameter("txtName");
response.getContetType("text/html");
PrintWriter out = response.getWriter();
out.println("Welcome,"+name);
out.close();
}
}
In order to compile servlets implementation classes of Servlet API must be available in classpath. These classes are not provided as core Java library rather these are provided by web server or application server vendors.
Different vendors provide these classes through different jar files for ex –
1) Tomcat – servlet.api.jar
2) Weblogic server – weblogic.jar
3) GlassFish App Server – j2ee.jar
Each web application is self describing i.e. it contains information of all its components in xml format through an XML file named web.xml
It contains following elements :-
<web-app> – root element of web.xml file
<servlet> is the sub element web-app that is used to describe the servlet. It contains following sub-element –
a) <servlet-name> – unique identifier for servlet
b) <servlet-class> – fully qualified name for the servlet class
<servlet-mapping> is a sub element of <web-app> that is used to map incoming request to a servlet. It contains following sub-element –
a) <servlet-name> – Unique identifier
b) <url-pattern> – URL used by client to invoke servlet
web.xml for HelloServlet
<web-app>
<servlet>
<servlet-name> s1 </servlet-name>
<servlet-class> First Servlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> s1 </servlet-name>
<url-pattern> helloServlet </url-pattern>
</servlet-mapping>
...
</web-app>
1.0 – Request for HelloServlet is received
1.1 – Using the URL servlet mapping element of web.xml is identified
1.2 – From the <servlet-mapping> element <servlet name> is picked which is used to identify <servlet> element. From the servlet element name of servlet class is identified.
Passing Initialization Parameters to Servlets –
Initialization parameters represents data that is provided by the application developer to the servlets of an application through web.xml
Initialization parameters is of 2 types –
1) Application scope init parameters
2) Servlet specific init parameters
1) Application scope initialization parameters are defined by application developer using <context-param> sub element of <web-app> in web.xml file.
<web-app>
<context-param>
<param-name> Name </param-name>
<param-value> Value </param-value>
</context-param>
.....
</web-app>
Application scope initialization parameters are made available to all the servlets of an application by the application server.
An object of type javax.servlet.ServletContext is used by the application server to provide application scope initialization parameters to servlets.
For each application WebServer creates an object of type ServletContext at the time of deployment. This object serves following 3 purposes –
1) It is used by application developer to share data between servlets i.e. servlets can save data in the form of attributes in this object.
2) Application scope initialization parameters are provided to servlets using this object.
3) This object acts as interface between web server and application
2) Servlet specific initialization parameters are defined using <init-param> sub element of servlet in web.xml file
<web-app>
<servlet>
<servlet-name> .. </servlet-name>
<servlet-class> .. </servlet-class>
<init-param>
<param-name> ParameterName </param-name>
<param-value> value </param-value>
</init-param>
...
</servlet>
...
</web-app>
For each servlet web server creates an object of type ServletConfig. This object serves following purpose –
1) It is used by the web server to provide the reference of ServletContext to the servlet.
2) It is used by the web server to provide servlet specific initialization parameters to the servlet.
App Developer WebServer ServletContext ServletConfig Servlet
1.0 – Web application is deployed by App Developer
1.1 – ServletContext object is created for application by WebServer
1.2 – Application scope initialization parameters are read from web.xml and are saved in ServletContext object by WebServer.
2.0 – Initial request for a servlet is received
2.1 – Servlet object is created by WebServer
2.2 – ServletConfig object is created by WebServer
2.3 – Reference of ServletContext object is saved in ServletConfig object by WebServer
2.4 – Servlet specific initialization parameters are read from web.xml and are saved in ServletConfig object by WebServer.
2.5 – Reference of ServletConfig object is provided to Servlet in init() method by WebServer.
Ex for LoginServlet
ServletConfig config = getServletConfig();
servletContext ctx = config.getServletContext();
Class.forName(ctx.getInitParameter("driverClass"));
Connection con = DriverManager.getConnection(ctx.getInitParameter("url"),ctx.getInitParamter("user"),ctx.getInitParameter("password"));
Advantage of this code is that we don’t have to hard code the values in our java class.
State Management
Http is a protocol that is used to send request and receive response from web servers i.e. a stateless protocol i.e for each request a new http connection is created between the client and web server. This connection is closed as soon as response is received by the client.
The major drawback of the stateless protocol is that server fails to recognize series of logically related request coming from a client.
The problem of State Management deals with the maintenance of state between requests so that server can identify relation between these requests.
Following 4 methods are used for this purpose –
1) Cookies 2) Hidden Form Field
3) URL Rewriting 4) HttpSession Object
1) Cookie
It represents textual information in the form of key value pair that is sent by server as part of response to the client machines. This information is sent by the browser to server with subsequent requests.
javax.servlet.http.Cookie class represents cookies in a web application.
addCookie() method of httpServletResponse interface is used to send a cookie as part of response.
Ex –
Cookie ck = new Cookie("user",name);
ck.setMaxAge(50000);
response.add(ck);
getCookie() method of httpServletRequest interface is used to obtain the reference of cookies received as part of request.
Ex –
Cookie ck[] = request.getCookies();
name = ck[0].getValue();
2) Hidden Form Field
In this method information to be persisted between one request to another is contained in invisible text fields which are added to the response page.
Whenever a new request is submitted from this page value of invisible text fields is sent as request parameters.
out.println("<br> <input type=hidden name=txtHidden value=\" "+name +"\">");
To get this parameter
String name = request.getParameter("txtHidden");
3) URL Rewriting
In this approach information to be persisted between one request to another is appended dynamically to the URL of the page on which information is required i.e. whenever a new request is submitted using the URL information is made available on the server as Request Parameters.
Ex –
out.println("<br> <a href = \"sorryServlet?userName="+name+"\"> Take a tour </a>");
4) HttpSession
In all three methods information to be persisted between requests is sent to the client machine in one form or another i.e. a round trip of information is involved.
In the 4th method information to be persisted between request is stored on the server in an object of type HttpSession.
HttpSession session = request.getSession();
session.setAttribute("name",name);
At time of retrieving
HttpSession session = request.getSession();
String name = (String)session.getAttribute("name");
Filter
It is an optional component of a web application that intercept request and may apply pre and post processing. It sits between WebServer and Servlet.
Following interface facilitate development of filters –
1) Filter
2) FilterChain
3) FilterConfig
1) Filter interface provides lifecycle method of filter. It contains following methods –
a) init() – is invoked only once just after a filter object is created. It is used by the Web Server to provide the reference of FilterConfig object to the filter.
public void init(FilterConfig config)
b) doFilter() – is invoked each time a request for the resource on which filter is applied is received.
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException
c) destroy() – is invoked only once just before a filter is unloaded.
2) FilterConfig – for each filter Web Server creates an object of type FilterConfig. This object serves 2 purpose –
a) It is used by the Web Server to provide the reference of ServletContext to the filter.
b) It is used by the Web Server to provide initialization parameters to the filter.
3) FilterChain – For each chain of resources WebServer creates an object of type FilterChain. This object provides the abstraction of forwarding request to the next resource in the chain. It contains 1 method –
public void doFilter(ServletRequest req, ServletResponse res) throws ServletException, IOException
This method is used by filter to invoke the next resources in the chain.
In order to create a filter implementation of Filter interface is need to be provided.
Following elements are to be added to web.xml to apply a filter on a resource.
<web-app>
<filter>
<filter-name> Unique Identifier </filter-name>
<filter-class> Fully Qualified Class Name </filter-class>
<init-param>
<param-name> Name of paramter </param-name>
<param-value> Value of parameter </param-value>
</init-param>
---
</filter>
<filter-mapping>
<filter-name> Unique Identifier </filter-name>
<servlet-name> Name of target servlet </servlet-name>
<url-pattern> url of target resource </url-pattern>
</filter-mapping>
---
</web-app>
public class MyFilter implements Filter
{
FilterConfig config;
public void init(FilterConfig c)
{
config = c;
}
public void destroy()
{ }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
{
System.out.println("Filter is invoked");
//pre-processing logic
chain.doFilter(request,response);
//post processing logic
System.out.println("Filter exiting");
}
}