Sunday 2 May 2010

Servlet Interview Questions and Answers

Web Application Structure


Example program for Filter

//Home.html
<html>
 <body>
<form method=post action="ser1">
<input type="submit" value="Invoke TestServlet using path /ser1"/>
</form><br><br>
<form method=post action="ser2">
<input type="submit" value="Invoke TestServlet using path /ser2"/>
</form>
 </body>
</html>
//TestServlet.java
//TestServlet
package com.rajendra.servlets;

import javax.servlet.*;
import java.io.*;

public class TestServlet extends GenericServlet {

public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException {

PrintWriter out=res.getWriter();
out.println("In TestServlet, processing request<br/>");
}//service
}//class
//Creating MyFilter1.java
//Filter
package com.rajendra.servlets;

import javax.servlet.*;
import java.io.*;

public class MyFilter1 implements Filter {

public void init(FilterConfig fc){}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("In MyFilter1, filtering Request...<br/>");

fc.doFilter(req,res);

//Post Processing can be performed here if any
out.println("In MyFilter1, filtering Response...<br/>");
}//doFilter

public void destroy() {}
}//class
//MyFilter2.java
//Filter
package com.rajendra.servlets;

import javax.servlet.*;
import java.io.*;

public class MyFilter2 implements Filter {

public void init(FilterConfig fc){}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("In MyFilter2, filtering Request...<br/>");

fc.doFilter(req,res);

//Post Processing can be performed here if any
out.println("In MyFilter2, filtering Response...<br/>");
}//doFilter

public void destroy() {}
}//class
//Configuring the Filter Application
<!--web.xml-->
<web-app>
<filter>
<filter-name>filter1</filter-name>
<filter-class>com.santosh.servlets.MyFilter1</filter-class>
</filter>
<filter>
<filter-name>filter2</filter-name>
<filter-class>com.santosh.servlets.MyFilter2</filter-class>
</filter>

<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/ser1</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name> 
<servlet-name>ts1</servlet-name>
</filter-mapping>
<!--
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/ser2</url-pattern>
</filter-mapping>
-->
<servlet>
<servlet-name>ts1</servlet-name>
<servlet-class>com.santosh.servlets.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ts1</servlet-name>
<url-pattern>/ser1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ts1</servlet-name>
<url-pattern>/ser2</url-pattern>
</servlet-mapping>
</web-app>



Servlet Filter

Filter

Introduction:
·         As we know that how to manage session (Session management, HttpSession) in web application.
·         And if we want to make sure that a resource( jsp, servlet, etc) is accessible only when user session is valid, we can achieve this by using servlet session attributes.
·         But if we have a huge number of servlets and jsps, then it will become hard to maintain because of redundant(repeated) code.
If we want to change the attribute name in future, we will have to change all the places where we have session authentication.

What is Servlet Filter?
It is an Interface which is predefined in javax.servlet.Filter interface
A Servlet filter is an object that can intercept(stops) HTTP requests targeted at your web application. 
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content
By using the Servlet Filter class we can overcome the following problems:


Some common tasks that we can do with filters are:
·         Logging request parameters to log files.
·         Authentication and autherization of request for resources.
·         Formatting of request body or header before sending it to servlet.
Internationalization
·         Compressing the response data sent to the client.
Alter response by adding some cookies, header information etc.

Purpose of Servlet Filter

Intercept request from a client browser before it gets processed in the server
Intercept/manipulate response from server before it is sent to the client browser


Advantages of Servlet Filter

Servlet filter is pluggable
No dependency between filters
 




following diagram illustrates:



Servlets and filters both are unaware of each other and we can add or remove a filter just by editing web.xml.

We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml. We can create a Servlet Filter by implementing javax.servlet.Filter interface.
For more information http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html
Advantages of Filters:

  • Reusable code : that can transform the content of requests, responses, and header information from one format to another: Example: a web application that formats the data before it is presented to the client. And different clients require different formats such as Wireless Markup Language(WML), Excel Sheets, Portable Document Format(PDF) to do this we need of transformation of filtering in a Web application.
Work flow of Filter:
·         When the web container loads the filter class using the normal java class loading
·         This class may be loaded from a local file system, a remote file system, or other network services
·         If the web container fails to load the class, it terminates this initialization process.
·         After the filter class is loaded, the web container creates the object of Filter class. The Web container uses the no-argument constructor to create a new instance of the Filter class.
·         Once the Filter object is created, the web container initializes the Filter object by invoking init(0 and passing the FilterConfig object reference to this method.
·         FilterConfig object allows the Filter object to access name-value configured initialization parameters, the reference to the ServletContext interface for the Web Application, and other container specific details.
·         The Web Container creates one FilterConfig object per filter declaration in the deployment descriptor.
·         The init() reads the configuration data and initialize resources, then the Web container keeps the Filter object into active state that is it makes it available and ready to handle requests, Otherwise, if the filter fails to initialize, it throws the UnavailableException. If the init(0 of Filter interface throws an exception, the Web container does not put this object into the active state. That is it removes the object.
·         After deploying the web application or before the request is sent to the Web container to access a Web resource, the container locates the list of filters that must be applied to the Web resource.
·         When the container receives the request, it takes the first filter object from the list and calls its doFilter() method passing ServletRequest, ServletResponse and a reference of the FilterChain object that it uses.
·         The doFilter() method of a Filter performs preprocessing, such as examining the request’s headers, wrapping the request and / or response object passed into its doFilter() method with a customized implementation of ServletRequest, or HttpServletRequest and / or ServletResponse or HttpServletResponse respectively to modify request/response headers or data.
·         After performing all its preprocessing operations, if any, the filter may call doFilter() on FilterChain object passing in the request and response objects.
·         The doFilter() method of FilterChain is responsible to invoke the next entity in the chain.
·         The next entity may be another filter, or if the filter making the invocation is the last filter configured for this chain then the next entity is the target web resource.
·         Otherwise filter can block the request by not making the call to invoke the next entity, that is by not calling doFilter() on FilterChain object.
·         After doFilter() method invocation on theFilterChain object, filter can perform post processing operations.
·         The destroy() method is called either after all threads have completed their functionality or when thread’s timeout period elapses. This method detaches all resources such as memory and threads from filter instance.

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>ServletFilter</display-name>
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.tech2money.HelloServlet</servlet-class>

    </servlet>
    <servlet-mapping>

        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>HalloFilter</filter-name>

        <filter-class>com.tech2money.HalloFilter</filter-class>

    </filter>



    <filter-mapping>

        <filter-name>HalloFilter</filter-name>

        <url-pattern>/HelloServlet</url-pattern>

    </filter-mapping>


    <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

</web-app>


Example of basic Servlet Filter class

package com.rajendra;
import javax.xml.crypto.dsig.spec.XPathType.Filter;
public class HalloFilter extends Filter {
/**
     * init() is called by the web container to indicate to a filter that it is being placed into service.

     * @param config

     * @throws ServletException

     */

    public void init(FilterConfig config) throws ServletException {

        // Get init parameter which is defined in the <init-param> tag in web.xml for filter definition

        String initParam = config.getInitParameter("init-Param");



        // Print the init parameter

        System.out.println("Init Param: " + initParam);

    }



    /**

     * doFilter() is called by the container each time a request/response pair is passed through the chain due to a

     * client request for a resource at the end of the chain.

     * @param request

     * @param response

     * @param chain

     * @throws java.io.IOException

     * @throws ServletException

     */

    public void doFilter(ServletRequest request, ServletResponse response,
30
            FilterChain chain) throws java.io.IOException, ServletException {



        // Get the IP address of client machine.

        String ipAddress = request.getRemoteAddr();



        // Log the IP address and current timestamp.

        System.out.println("IP " + ipAddress + ", Time "+ new Date().toString());



        // Pass request back down the next resource

        chain.doFilter(request, response);

    }



    /**

     * destroy() is called by the web container to indicate to a

     * filter that it is being taken out of service.

     */

    public void destroy() {

        /*

         * Called before the Filter instance is removed from service by the web

         * container

         */

    }

}

Saturday 1 May 2010

Example program for HttpSessionListener

/*MySessionListener.java*/
package com.rajendra.servlets;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener
{
public MySessionListener() {
    }
  public void sessionCreated(HttpSessionEvent sessionEvent) {
  // Get the session
  HttpSession session = sessionEvent.getSession();
   try {
   System.out.println("Session created: "+session);
  session.setAttribute("foo","bar");
  } catch (Exception e) {
System.out.println("Error in setting session attribute: "+ e.getMessage());
 }
 }
 public void sessionDestroyed(HttpSessionEvent sessionEvent) {
 // Get the session that was invalidated
  HttpSession session = sessionEvent.getSession();
  // Log a message
  System.out.println("Session invalidated: "+session);
  System.out.println("The name is: " + session.getAttribute("foo"));
}
}
/*ServletSessionListener.java*/
package com.rajendra.servlets;
import java.io.IOException;
import java.io.PrintWriter;

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

public class ServletSessionListener extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session= request.getSession();
String str = (String)session.getAttribute("foo");
pw.println("The name is " + str);
}
}


  1. maintain the folder structure
  2. write the web.xml file
  3. \

What is HttpSessionListener

·         We knew that Http protocol is a “stateless” protocol means it can not remember the previous transactions.
·         When client sends a request to the servler, the server receives the request and processes the request and sends back the response to the client.
·         After sending the response the server to the client, the server closes the connection and forgets about the previous requests.
·         If the client sends the request to the server again, the server treats each request as a new request.
·         So to remember the server of each transaction of client request we use the session.
·         In session tracking when the client sends the request to the server then server creates a unique id for that request and sends back the unique id to the client along with the response object, and when a client sends the request to the server it also sends a unique id with it so that the server remember from where the request is coming.
What is Listeners:
Listeners listen the events. Whenever any event occurs it is listened by the listener object. The listener object is controlled by the web servers. Listeners allow developers to recognize the lifecycle events of a web application so that they can perform common tasks. For example: 

  •  A developer can execute the code for initializing a database when an instance of a Web application is created. 
  • Here, creating an instance( object) of a web application is an event. The listener Application Programming Interface (API) has predefined methods to listen to such events.
HttpSessionListener is an interface which extends java.util.EventListener class. The main purpose of this listener is to notify whenever there is a change in the list of active sessions in a web application 
This interface has  two methods:
  1. sessionCreated(HttpSessionEvent event): It will notify when the session is created.
  2. sessionDestroyed(HttpSessionEvent event): It will notify when the session gets invalidated.
In the above methods we can see that we have used HttpSessionEvent as the parameter of both the methods. This class has only one method getSession() which returns the current session.

forward method example program



<html>
<head>
<title>Home Page</title>
</head>
<body>
<h2 align="center">Welcome</h2>
<h3>This is your home page.</h3>
</body>
</html> 
//ForwaredRequestDispatcher.java
package com.rajendra.servlets;
import java.io.PrintWriter;

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

public class ForwaredRequestDispatcher extends HttpServlet {

        protected void doGet(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException,      IOException 
     {
              response.setContentType("text/html");
                PrintWriter out=response.getWriter();
                ServletContext context=getServletContext();
                RequestDispatcher requestDispatcher=context.getRequestDispatcher("/index.html“);
                requestDispatcher.forward(request, response);
                
                }
        }



//web.xml

<web-app>

<servlet>

<display-name>RequestDispatcherExample</display-name>
<servlet-name>RequestDispatcherExample</servlet-name>
<servlet-class>com.rajendra.servlets.RequestDispatcherExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RequestDispatcherExample</servlet-name>
<url-pattern>/RequestDispatcherExample</url-pattern>
</servlet-mapping>
</web-app> 

//before executing this program maintain the folder structure

include method example program


//index.jsp
<%@page contentType="text/html" 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>index.jsp</title>
</head>
<body>
<h3> Message from the index.jsp </h3>
</body>
</html>

//MyServlet.java
package com.rajendra.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("currently in the MyServlet ");

RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.include(request, response);

out.println("back to the MyServlet ");
out.println("</body>");
out.println("</html>");
}
}

  1. //maintain the folder structure
  2. create WEB-INF folder
  3. under WEB-INF folder create "classes" and web.xml file
  4. go to classes and paste the class file of MyServlet.java
  5. to to WEB-INF folder and open web.xml in a note pad , paste the following code:
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.rajendra.servlets.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>MyServlet</welcome-file>
</welcome-file-list>