Monday, June 25, 2018

Form Processing using Servlet

Form Processing using Servlet example:
       I am giving a example program for processing the form as shown below from JSP to Servlet using Eclipse IDE

  
Step 1: Open the Eclipse
Step 2: File -> New -> Dynamic Web Project
            New Dynamic Web Project window opens as shown below. Enter the Project name and click Next.


Step 3: Click on Next button again.


Step 4: Select the Generate Web.xml deployment descriptor and click Finish.

 
Step 5: Now the Dynamic Web Project is created and start coding the Project. The folder structure for this example is shown below.





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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>Servlet_Samples</display-name>
 
  <welcome-file-list>
    <welcome-file>FormProcessing.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
    <description></description>
    <display-name>FormInputProcessingServlet</display-name>
    <servlet-name>FormInputProcessingServlet</servlet-name>
    <servlet-class>formprocessing.FormInputProcessingServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>FormInputProcessingServlet</servlet-name>
    <url-pattern>/FormInputProcessingServlet</url-pattern>
  </servlet-mapping>

  </web-app>

FormProcessing.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Processing</title>
</head>
<body>
<h1>Form Processing</h1>
<form action="FormInputProcessingServlet" method="get">

<label for="name">Name</label>
<input type="text" name="name" id="name">
 <br>
<label for="course">Select the course</label>
<input type="checkbox" name="course" value="Servlet" id="course">Servlet
<input type="checkbox" name="course" value="JSP" id="course">JSP
<input type="checkbox" name="course" value="Struts" id="course">Struts

<br>

<label for="qualification">Qualification</label>
<select name="qualification" id="qualification">
<option>B.SC.</option>
<option>BE</option>
<option>MCA</option>
</select>

<br>
<label for="Gender">Gender</label>
  <input type="radio" name="sex" value="male" id="male" />
  <label for="male">Male</label>
  <input type="radio" name="sex" value="female" id="female" />
  <label for="female">Female</label>
<br>   
    <input type="submit" value="submit">
</form>
</body>
</html>


FormInputProcessingServlet.java

package formprocessing;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FormInputProcessingServlet
 */
public class FormInputProcessingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FormInputProcessingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void init() throws ServletException
    {
    System.out.println("Init Called");
    }
   
    public void destroy()
    {
    System.out.println("Destroy Called");   
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String sname=request.getParameter("name");
        String scourse[]=request.getParameterValues("course");
        String squalification=request.getParameter("qualification");
        String sgender=request.getParameter("sex");
        out.println("Name:"+sname);
        out.println("<br>Courses Completed:"+Arrays.toString(scourse));
        out.println("<br>Qualification:"+squalification);
        out.println("<br>Gender:"+sgender);
       
    }

}

Export to war:
  • Right click on the application and select export -> war file and deploy the war in the server.

Note: To Run this application, javax.servlet.jar is required.

Click to download: javax.servlet.jar

Reading Form Data using Servlet


Servlets handles form data parsing automatically using the following methods depending on the situation:
  • getParameter()
  • getParameterValues()
  • getParameterNames()

getParameter() :
      Used to get the value of a form parameter.
                 String paramvalue = request.getParameter("param_name"); 

getParameterValues():
       Used to get the parameter appears more than once and returns multiple values, for example checkbox.
                 String[] paramValues = request.getParameterValues(paramName);

getParameterNames():
        Used to get the complete list of all parameters in the current request.
                  Enumeration paramNames = request.getParameterNames();
                  while(paramNames.hasMoreElements()) {
                            String paramName = (String)paramNames.nextElement();
                   }

 

Web Application Folder Structure

Web Application Folder Structure:


Application Server and Web Server

Web Server:
  • Web Server is designed to serve HTTP Content.
  • Serves content to the web using http protocol.
  • Web servers are well suited for static content, most of the production environments have web server acting as reverse proxy to app server.
            Eg: Apache
Application Server:
  • Application Server can also serve HTTP Content but is not limited to just HTTP. It can be provided other protocol support such as RMI/RPC.
  • Hosts and exposes business logic and processes.
  • Application servers are well suited for dynamic content.
           Eg: Tomcat, Weblogic, Jboss, IBM

Life Cycle of Servlet

Three Life Cycle Methods of Servlet:
  1. init
  2. service
  3. destroy
    init Method:
    •  The servlet is initialized by calling the init () method.
    •  The init method is designed to be called only once.
    • It is called when the servlet is first created, and not called again for each user request.
    • When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate.
                Signature of the init() method:
                       public void init() throws ServletException {
                              // Initialization code...
                       }


    service Method:
    •  The service() method is the main method to perform the actual task.
    •  The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
    •  Each time the server receives a request for a servlet, the server create a new thread and calls service.
    • The service() method checks the HTTP request type (GET, POST, etc.) and calls doGet, doPost etc. methods as appropriate.
                  Signature of the service() method:
                       public void service(ServletRequest request, ServletResponse response)
                             throws ServlertException,IOException{
                           

                        }
    • So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
    • The doGet() and doPost() are most frequently used methods with in each service request.

    destroy Method:
    •  The destroy() method is called only once at the end of the life cycle of a servlet.
    •  This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
    •  After the destroy() method is called, the servlet object is marked for garbage collection.
    • servlet is garbage collected by the garbage collector of the JVM.

                   Signature of the destroy() method:
                         public void destroy() {
                               // Finalization code...
                         }


    HTTP Servlet Methods


    • doGet()
    • doPost()
    • doHead()
    • doPut()
    • doDelete()
    • doOptions()
    • doTrace()
    Get Method:
    • The GET method sends the encoded user information appended to the page request in the URL.
    • The page and the encoded information are separated by the ? character as follows:
                            http://www.test.com/hello?key1=value1&key2=value2
    • The GET method has size limtation: only 1024 characters can be in a request string.  
           Signature of the doGet() method:
                public void doGet(HttpServletRequest request, HttpServletResponse 
                      response) throws ServletException, IOException {
                               // Servlet code
                }

    Note: Never use get method to pass password or other sensitive information.

    Post Method:
    • More reliable method of passing information is the POST method.
    • Post method also packages the information exactly the same way as GET methods, but instead of sending it in the URL, it sends it as a separate message.
    • There is no limitation for the Post method.
           Signature of the doPost() method:
               public void doPost(HttpServletRequest request, HttpServletResponse response)    
                    throws ServletException, IOException {
                            // Servlet code
               }


    Servet Class Hierarchy





    • Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition.
    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.
     
    Method
    Description
    public void init(ServletConfig config)
    Initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.
    public void service(ServletRequest request,ServletResponse response)
    Provides response for the incoming request. It is invoked at each request by the web container.
    public void destroy()
    Invoked only once and indicates that servlet is being destroyed.
    public ServletConfig getServletConfig()
    Returns the object of ServletConfig.
    public String getServletInfo()
    Returns information about servlet such as writer, copyright, version etc.

    Generic Servlet Abstract Class

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

    There are many methods in GenericServlet class. They are as follows:
    1. public void init(ServletConfig config) is used to initialize the servlet.
    2. public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.
    3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.
    4. public ServletConfig getServletConfig() returns the object of ServletConfig.
    5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
    6. public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)
    7. public ServletContext getServletContext() returns the object of ServletContext.
    8. public String getInitParameter(String name) returns the parameter value for the given parameter name.
    9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.
    10. public String getServletName() returns the name of the servlet object.
    11. public void log(String msg) writes the given message in the servlet log file.
    12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace. 
    HttpServlet Abstract Class

    The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. 

    There are many methods in HttpServlet class. They are as follows:
    1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.
    2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.
    3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.
    4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.
    5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.
    6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.
    7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.
    8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.
    9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container. 
    10. protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT.

    Servlet Introduction

    Servlet:
    • Servlet is a server side java objects.
    • Servlets are programs that run on a Web or Application server.
    • Servlet is used to create dynamic web pages.
    • For servlet, only one object is created and each request is handled by threads.
    • so, Servlet is not a Thread safe by default.
    • By Synchronizing, we can make servlet as Thread safe.
    • Servlet act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server 
    Request and Response:
    • It Contains header and data
    Request URL Format:
    • PROTOCOL://HOST:PORT/CONTEXT/RESOURCE
              Eg: http://192.168.192.59:8080/Application name/web page