Tuesday, June 26, 2018

Servlet Config Interface


  • An object of ServletConfig is created by the web container for each servlet.
  • This object can be used to get configuration information from web.xml file.
  •  If the configuration information is modified from the web.xml file, we don't need to change the servlet.
Methods of Servlet Config Interface

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
  3. public String getServletName():Returns the name of the servlet.
  4. public ServletContext getServletContext():Returns an object of ServletContext.
Syntax to Call the methods of ServletConfig interface

ServletConfig config=getServletConfig();  

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

<web-app> 
  <servlet> 
    ...... 
     
    <init-param> 
      <param-name>parametername</param-name> 
      <param-value>parametervalue</param-value> 
    </init-param> 
    ...... 
  </servlet> 
</web-app>


 Example of ServletConfig to get initialization parameter

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.


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 out = response.getWriter(); 
         
        ServletConfig config=getServletConfig(); 
        String driver=config.getInitParameter("driver"); 
        out.print("Driver is: "+driver); 
             
        out.close(); 
        } 
     
    }  


Web.xml

<web-app> 
     
    <servlet> 
    <servlet-name>DemoServlet</servlet-name> 
    <servlet-class>DemoServlet</servlet-class> 
     
    <init-param> 
    <param-name>driver</param-name> 
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> 
    </init-param> 
     
    </servlet> 
     
    <servlet-mapping> 
    <servlet-name>DemoServlet</servlet-name> 
    <url-pattern>/servlet1</url-pattern> 
    </servlet-mapping> 
     
    </web-app>


Example of ServletConfig to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.

DemoServlet.java

    import java.io.IOException; 
    import java.io.PrintWriter; 
    import java.util.Enumeration; 
     
    import javax.servlet.ServletConfig; 
    import javax.servlet.ServletException; 
    import javax.servlet.http.HttpServlet; 
    import javax.servlet.http.HttpServletRequest; 
    import javax.servlet.http.HttpServletResponse; 
     
     
    public class DemoServlet extends HttpServlet { 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
     
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
         
        ServletConfig config=getServletConfig(); 
        Enumeration<String> e=config.getInitParameterNames(); 
             
        String str=""; 
        while(e.hasMoreElements()){ 
        str=e.nextElement(); 
        out.print("<br>Name: "+str); 
        out.print(" value: "+config.getInitParameter(str)); 
        } 
             
        out.close(); 
    } 
     
    }


Web.xml

<web-app> 
     
    <servlet> 
    <servlet-name>DemoServlet</servlet-name> 
    <servlet-class>DemoServlet</servlet-class> 
     
    <init-param> 
    <param-name>username</param-name> 
    <param-value>system</param-value> 
    </init-param> 
     
    <init-param> 
    <param-name>password</param-name> 
    <param-value>oracle</param-value> 
    </init-param> 
     
    </servlet> 
     
    <servlet-mapping> 
    <servlet-name>DemoServlet</servlet-name> 
    <url-pattern>/servlet1</url-pattern> 
    </servlet-mapping> 
     
    </web-app>  

Request Dispatcher

  • The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.
  • This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.  

Two Methods of Request Dispatcher:
  1. Forward
  2. Include

    Syntax:
              RequestDispatcher rd = request.getRequestDispatcher("/URL Pattern of Destination Servlet");
              rd.forward(request,response);   //Forward
              rd.include(request,response);    //Include
     
    Send Redirect
    • The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.  

    Syntax:
              response.sendRedirect("/URL Pattern of Destination Servlet");    //Redirect


    forward() method
    sendRedirect() method
    The forward() method works at server side.
    The sendRedirect() method works at client side.
    It sends the same request and response
    objects to another servlet.
    It always sends a new request.
    It can work within the server only.
    It can be used within and outside the server.


    Note: 
    • In Forward and Include, the URL will not change.
    • In Redirect URL will be changed.

    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