Monday, 16 November 2015

Servlets

Servlets are server side java classes. Servlet container is needed to execute these serverside java classes. They are capable to read data coming from browser. Data from browser is sent using http protocol. The data can be sent either thru header(query string) or body(payload) of HTTP protocol.
The servlet container can understand the http data. It will accept the http protocol data and read it. It will make the http protocol data into java bean object(HttpServletRequest). It will then forward HttpServletRequest to servlet classes.

Servlet classes will generate HttpServletResponse object and container will convert into http protocol data.  The http protocol data will be forwarded to the browser. 

Servlet container responsibilities:
  • Read http request data and convert to HttpServletRequest object.
  • Based on the browser request url/address, create servlet object(if first call) and pass HttpServletRequest object data to servlet
  • Convert HttpServletResponse into Http protocol data. And send the response to browser.
Note: Container will prepare servlet object for the initial/first request(all the servlets are singleton classes).

Directory structure for Servlet:
  • Servlet container will accept well directory structured application. 
  • Application Folder -> Its name will be application name.
    • view resources -> html, css, java script, jsp, image, audio & video
    • WEB-INF -> folder
      • web.xml -> mapping information
      • classes -> folder. This will have servlet classes & Model(jdbc, spring, simple java) classes
      • lib  -> folder  -> additional api's. like file upload api, spring related jar files.

How to write a servlet 
There are 3 servlet implementations. A servlet class can be created either by implementing the interface or extending the following classes.
  • servlet interface
  • Generic servlet (Child of servlet interface) . Its an abstract class
  • HTTP servlet - Abstract class.
Servlet Interface
  • void init(javax.servlet.ServletConfig)
  • void service(ServletRequest, ServletResponse)
  • void destroy()
  • String getServletInfo()
  • String ServletConfig getServletConfig()
Generic Servlet -  It is child of Servlet interface
  • Only one single abstract method. Other methods are implemented. 
  • void service(ServletRequest, ServletResponse) -> needs implementation
  • Session management is not possible in this case.
HTTP Servlet -  All methods are concrete, even though the class is abstract
  • recommendation is to override following methods
  • doGet(HttpServletRequest, HttpServletResponse)
  • doPost(HttpServletRequest, HttpServletResponse)
  • Session management is possible in this case.

Eg using Servlet Interface
  import   javax.servlet.*;

  public class HelloServlet implements Servlet{
      public void init() { }
      public void service(ServletRequest req, ServletResponse resp) throws ServletException {
            String name=req.getParameter("ParamName");
            resp.setContentType("text/html");
            PrintWriter out=  resp.getWritter;
            out.println("hello "+name);
            }
      public void destroy(){  }
      public String getServletInfo() {  return null; }
      public String ServletConfig getServletConfig() { return null; }
     
}

Sevlet Lifecycle -
  • Containers role(when it is started)
    1. Extracts all WAR files and stores(deploys) the application in webapps folder
    2. Reads web.xml file and creates 2 objects, ServletContext & ServletConfig.
      ServletContext is accessible by every servlet in the application. ServletConfig is specific/private to a servlet.
    3. Creates Servlet Object and executes init() passing ServletConfig object as parameter
Create Servlet from eclipse
  • Create dynamic web project
  • add view pages under webcontent
  • add servlet classes in java resources/src folder
  • sample web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ServletLifeCycle</display-name>
  <welcome-file-list>
    <welcome-file>registration.html</welcome-file>
  </welcome-file-list>
  <servlet>
      <servlet-name>reg</servlet-name>
      <servlet-class>RegistrationServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>reg</servlet-name>
      <url-pattern>/RegServlet</url-pattern>
  </servlet-mapping>
</web-app>
We can configure configurations data and context data in web.xml

Context & Config
  init parameters are local for a servlet and Context parameters for global

Http Servlet
  • For each browser(until open to close), it maintains session object with unique session id.
  • It maintains sessions 
  • It maintains browser caches
  • HttpSession hs = request.getSession(); // to get session object
Inter Servlet Communication
  • getServlet("<servletname">)
    • getServletContext().getServlet("PrintServlet").doGet(req, res); //not recommended
  • requestDispatcher
    •  request.getRequestDispatcher("PrintServlet").forward(req,res);
    •  request.getRequestDispatcher("PrintServlet").include(req,res);
  • sendRedirect
Filters:
  • It is to validate the input data, security and so
  • Filter Object is created during deployment time itself.
  • Filter will execute 2 times. Before data is submitted to servlet, and when servlet output is returned back via Filter
    • filterChain.doFilter(req,response) - call servlet and then continues after Servlet execution is complete.
  • It comes with 3 methods
    • init(FilterConfig)
    • doFilter(ServletRequest, ServletResponse, FilterChain)
    • destroy()
  • How to create?
    • Create a Filter implementing javax.servlet.Filter(web.xml entries same as Servlet)
    • url pattern should be same as that of respective servlet for which it acts as Filter
    •  
Servlet Listners:
  Servlet Container has some event handlers. - On start of container, on stop of container. The event handler is ServletContextListner

Listners will be instantiated and executed prior to Filters & Servlets during initialization and executes after Servlet & Filter during destroy.
  • ServletContextListner
    • contextInitialized(ServletContextEvent sce)  //on container start
      • When container is started, it creates ServletContext object, and instantiates Listnerclass that implements ServletContextListner and executes contextInit()
    • contextDestroyed(ServletContextEvent sce) //on container stop
    •  Uses: Initialization required for entire application like - jndi object, connection pool object
  Servlet Session has some event handlers(Session Listener handlers). - On start of session, on invalidate of session. The event handler is ServletSessionListner
  • ServletSessionListner  interface
    • sessiontInit()  //at the time of creating session object httpreq.getSession()
    • sessionDestroy() //on session invalidate

  Servlet Request has some event handlers(Servlet Request Listener). - On start of request, on destroy of request. Request and Response objects will be destroyed after sending response to client.

The event handler is ServletSessionListner
  • ServletRequestListner  interface
    • requestInit()  //at the time of creating request object
    • requestDestroy() //on destroy of request object
How to create Listner-
  •   Eclipse - new Listner class -> It configures listner class in web.xml using Listner and Listner-class tags

MVC Architecture- Controller responsibility is to read data and send into model.

JSP
  • To generate dynamic webpages(Java script executes on browser/client machine, where as JSP executes on server
  • JSP container is required to run JSPs,
  • JSP container convers jsp into Servlet java class
  • JSP pages can containe both HTML and java code
  • <%!        %> is a declaration tag. This is used for declaration, jsp init and jsp destroy
  • <%! _jspInit(){}       %>  to place the code into init() method
  • <%! _jspDestroy(){}       %>  to place the code into destroy() method
  • <%        %>  is a scriplet tag. This code will be placed in service() method
  •  <%=        %>  is an expression. This is equivalent to out.println()
  • HTML content will be placed under out.Println()
  • To print with in scriptlet, we should use out.println()
Print a dynamic table:
<table>
<tr> <th>Number</th> <th>Value</th> </tr>
 <%for(int i=0;i<10;i++){ %>
<tr> <td>Number =</td> <td><%= i+1%></td> </tr>

 <% }  %>
</table>

9 JSP predefined/builtin objects - Service method will create following implict variables .
  • context
  • session
  • request
  • response 
  • config
  • out
  • exception
  • page  //this
  • pageContext
JSP Include
  • To include different pages(html for header, footer and menu) into main page(jsp)
  • Following directives can be used to include pages into jsp
      • <jsp:include page="<page path>"  //soft link to page.
    • <@include file="<page path>"  // copies the file content
  •  

Response Send Redirect
  • response.sendRedirect("url"); - This will send page url to browser. The browser in turn sends request to the page(with new request and response objects)


No comments:

Post a Comment