Servlets Tutorail




1.Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.


2.GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementaion of all the methods of these interfaces except the service method


GenericServlet class can handle any type of request so it is protocol-independent.  







3.HttpServlet class










The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace.It is Http Specific
4.Servlet Life Cycle
1) Servlet class is loaded:The servlet class is loaded when the first request for the servlet is received by the web container.
2) Servlet instance is created:The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:
   public void init(ServletConfig config) throws ServletException  
4) service method is invoked
The web container calls the service method each time when request for the servlet is received. Notice that servlet is initialized only once.
   public void service(ServletRequest , ServletResponse) throws ServletException, IOException  


5) Destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc.
   public void destroy()  


5.Internal Flow of Execution
  1. When we Deploy the App Servlet Container Reads the web.xml, if <load-on-startup> is there, then its loads the Servlet and create the Servlet Object.
  2. Other wise when the First Request comes Container creates Servlet Object, and calls init(ServletConfig) method by passing Config Object
  3. init() method internally calls Service(-,-)  methods and returnds the Result
  4. If protected service(HttpReq, HttpRes) is call, protected service method calls the doGet()
  5. Responce pass to Clinet, and Container calls destory() method


6.Request Paramters
these are called Request Paramereters


We can get these Parameters by request Object by using following methods.
  1. public String getParameter(String name) : is used to obtain the value of a parameter by name.
  2. Enumeration getParameterNames() : returns an enumeration of all of the request parameter names.
  3. public String[] getParameterValues(String name) : returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box.
7.Servlet Chaining
i. rd.forward(req,res)
ii.rd.include(req,res)
iii.responce.sendRedirect(url)

RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp


The RequestDispatcher interface provides two methods. They are:
1. public void forward(request,response)throws ServletException,IOException(Discards Intered Results)    
2. public void include(request,response)throws ServletException,IOException(Includes Intermdt results)


getRequestDispatcher() method used to get object of RequestDispatcher.call this by request/context object
1. RequestDispatcher rd=request.getRequestDispatcher("/servlet2");  
2. RequestDispatcher rd=context.getRequestDispatcher("/servlet2");
3. RequestDispatcher rd=context.getNamedDispatcher("logical naame of servlet");


Request Object : If the servlet is in same web Applcation of Same Server  do chainging by Request Object
Context Object : If the Servlet is in other web Application of Same Server do chaining by Context Object
response.sendRedirect(“url”) :: If the Servlet Other Server do chaining by using sendRedirect(Url);


RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
rd.forward(request, response);  
rd.include(request, response);
response.sendRedirect(“www.google.com”);


7.ServletConfig & ServletContext









8.Attribute in Servlet
An attribute is an object that can be set, get or removed from one of the following scopes:


  1. ServletRequest ,→ request  Attribute     → for only for Perticular Request
  2. HttpSession     → session  Attribute → for Session (Untill Browser Close)
  3. ServletContext → application  Attribute  →  for the Whole Application


There are following 4 attribute specific methods. They are as follows:


   public void setAttribute(String name,Object object):sets the given object in the application scope.
   public Object getAttribute(String name):Returns the attribute for the specified name.
   public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
  

9.Session Tracking
Session simply means a particular interval of time. Session Tracking is a way to maintain state of an user. Http protocol is a stateless protocol. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
 By Default HttpServlet is Stateless Protocal.for Making HttpServlet Statefull protocal for session mangement we have to use following  4 techniques
  1. Cookies
  2. Hidden Form Field  → <input type=”hidden” name=”a” value=”10”>
  3. URL Rewriting         → using rd.forward(), rd.include() already done
  4. HttpSession             → ses.setAttribute,ses.getAttribute / putValue using  session already done
1) Cookies
A cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.


javax.servlet.http.Cookie class API


Cookie(String name, String value): Constructs a cookie with a specified name and value.
   public void setMaxAge(int expiry):Sets the maximum age of the cookie in seconds.
   public String getName():Returns the name of the cookie. The name cannot be changed after creation.
   public String getValue():Returns the value of the cookie.
   public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
   public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.




10.Event and Listener in Servlet
Changing the state of an object is known as an event.




11.Filter
A filter is invoked at the preprocessing and postprocessing of a request.
Filter is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. So it will be easier to maintain the web application.


Filter API
Like servlet filter have its own API.The javax.servlet package contains the three interfaces of Filter API


  1.    Filter
  2.    FilterChain
  3.    FilterConfig


1) Filter interface
For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter.
  • public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  • public void doFilter(HttpServletRequest,HttpServletResponse ,FilterChain): doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
  • public void destroy():This is invoked only once when filter is taken out of the service.


2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only one method:
public void doFilter(HttpServletRequest, HttpServletResponse): it passes the control to the next filter or resource.


3.FilterConfig
An object of FilterConfig is created by the web container. This object can be used to get the configuration information from the web.xml file, like initParameters,ServletContext etc.
there are 4 methods in the FilterConfig interface.
  • public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  • public String getInitParameter(String parameterName): Returns the parameter value for the specified parameter name.
  • public Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter names.
  • public ServletContext getServletContext(): Returns the ServletContext object..htm#sthash.Jqd61j7G.dpuf
4)We can define filter same as servlet. Let's see the elements of filter and filter-mapping.in web.xml
<web-app>    
<filter>  
    <filter-name>...</filter-name>    
   <filter-class>...</filter-class>                               
</filter>     
<filter-mapping>  
     <filter-name>...</filter-name>  
     <url-pattern>...</url-pattern>  
</filter-mapping>  </web-app>
12.Servlet with Annotation (feature of servlet3):
Annotation represents the metadata. If you use annotation, deployment descriptor (web.xml file) is not requird.


@WebServlet(“/serv-name”): annotation is used to map the servlet with the specified name.it must be at the Top of servelt class
13.SingleThreadModel interface
The servlet programmer should implement SingleThreadModel interface to ensure that servlet can handle only one request at a time. It is a marker interface, means have no methods.


This interface is currently deprecated since Servlet API 2.4 because it doesn't solves all the thread-safety

1 Comments

Thank You

Previous Post Next Post