Grow Together Mentors Inspire Us In Life

Internet

Technology

Gadgets

Latest Release

Unknown

Introduction to Filter API

Introduction to Filter API

Filters are compontents that you can use and configure to perform some filtering tasks. Filter is used for pre-processing of requests and post-processing of responses. You can have any number of filters for pre-processing of a request and post-processing of a response. Filters are configured in the deployment descriptor of a web application.
filter api in servlet

How Filters Works?

  • When a request reaches the Web Container, it checks if any filter has URL patterns that matches the requested URL.
  • The Web Container locates the first filter with a matching URL pattern and filter's code is executed.
  • If another filter has a matching URL pattern, its code is then executed. This continues until there are no filters with matching URL patterns left.
  • If no error occurs, the request passes to the target servlet. Hence we know, that the request will be passed to the target servlet only when all the related Filters are successfully executed.
  • The servlet returns the response back to its caller. The last filter that was applied to the request is the first filter applied to the response.
  • At last the response will be passed to the Web Container which passes it to the client.

More about Filter API

Filter API is part of Servlet API. Filter interface is found in the javax.servlet package.
For creating a filter, we must implement Filter interface. Filter interface gives the following life cycle methods for a filter:
  1. void init(FilterConfig filterConfig): invoked by the web container to indicate to a filter that it is being placed into service.
  2. void doFilter(ServletRequest request, ServletResponse response, FilterChain chain): invoked 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.
  3. void destroy(): invoked by the web container to indicate to a filter that it is being taken out of service.

What is FilterChain Interface?

FilterChain object is used to invoke the next filter in the chain, or if the calling filter is the last filter in the chain then the rosource at the end of the chain invoked. The resources at the end of Filter chain can either be a target Servlet(in case of request flow) or the Client(in case of response flow) as described in the diagram above.

Declaring a Filter inside Deployment Descriptor

Declaring a filter inside deployment descriptor

Example demonstrating Filter usage

In this example we are using Filter to authenticate(check correct username and password). Here index.html will ask username and password from the user, MyFilter will validate the password entered by the user, if the user has entered "1234" as password, then he will be forwarded to first servlet else the index.html will be shown again to the user.
This is exactly what we used to do earlier using two servlet classes earlier, one for validation and the other to Welcome the user. Now we will insert a Filter for validating the user.
filter example

index.html
<form method="post" action="first">
    Name:<input type="text" name="user" /><br/>
    Password:<input type="text" name="pass" /><br/>
    <input type="submit" value="submit" />
</form>

web.xml
<web-app..>
    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <servlet-name>first</servlet-name>
    </filter-mapping>
    <servlet>
        <servlet-name>first</servlet-name>
        <servlet-class>first</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>first</servlet-name>
        <url-pattern>/first</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

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

public class MyFilter implements Filter {
 
    public void init(FilterConfig fc) throws ServletException {}
    
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        PrintWriter out = response.getWriter();
        String pass = request.getParameter("pass");
        if(pass.equals("1234"))
        {
         chain.doFilter(request, response);   
        }
        else
        {
            out.println("You have enter a wrong password");
            RequestDispatcher rs = request.getRequestDispatcher("index.html");
            rs.include(request, response);
        }
    }
   public void destroy() { }
}

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

public class first extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
     {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String user = request.getParameter("user");
        out.println("Wellcome "+user);
     }
}
Read More
Unknown

ServletRequestEvent and ServletRequestListener

ServletRequestEvent and ServletRequestListener

ServletRequestEvent class gives notification about lifecycle events for a ServletRequest. The source of the event is the ServletContext of the web application. ServletRequestListener receives the notifications generated by ServletRequestEvent and performs some specified tasks based on them.

Some Importants Methods of ServletRequestListener

MethodsDescription
void requestDestroyed(ServletRequestEvent e)is invoked when request is about to go out of scope of the web application..
void requestInitialized(ServletRequestEvent e)is invoked when request is about to come into scope of the web application.

Example

ServletRequestListener example

Hence one can easily implement the ServletRequestListener Interface and provide definitions to the two methods provided by it, requestDestroyed() and requestInitialized().
As the name suggests these methods will be called when request is initialized and when it is destroyed, hence we can use them for various purposes, like variable cleanup when request is destroyed, or performing some initial checks when request is received etc.

Read More
Unknown

HttpSessionEvent and HttpSessionListener

HttpSessionEvent and HttpSessionListener

HttpSessionEvent class gives notifications for changes to sessions within a web application. HttpSessionListener receives notifications of changes to the list of active sessions in a web application and perform some action. HttpSessionListener is used to perform some important tasks when a session is created or destroyed. For example: counting the number of active session.

Some other Session related Listeners

ListenerDescription
HttpSessionActivationListenerLet's you know when a session moves from one Virtual machine to another.
HttpSessionBindingListenerLe's your attribute class object get notified when they are added or removed from session.
HttpSessionAttributeListenerLet's you know when any attribute is added, removed or replaced in a session.

Methods of HttpSessionListener

MethodsDescription
void sessionCreated(HttpSessionEvent e)notification that a session was created.
void sessionDestroyed(HttpSessioEvent e)notification that a session was destroyed.

Example of HttpSessionListener

In this example we will create a session listener that will count the number of active sessions in a web application.

MySessionCounter.java
import javax.servlet.http.*;

public class MySessionCounter implements HttpSessionListener {

    private static int sessionCount; 
    
    public int getActiveSession()
    {
        return sessionCount;
    }
   
    public void sessionCreated(HttpSessionEvent e) 
    {   
        sessionCount++;  
    }

    public void sessionDestroyed(HttpSessionEvent e) 
    {
        sessionCount--;
    }
}

web.xml
<web-app ...>
<listener>
       <listener-class>MySessionCounter</listener-class>
</listener>
</web-app>

Read More
Unknown

What is ServletRequestAttributeEvent?

What is ServletRequestAttributeEvent?

ServletRequestAttributeEvent class gives notifications about changes to the attributes of ServletRequest in an application.
This class listens to the notifications and performs some important tasks whenever there is any change to the request attribute.

Some Important Methods of ServletRequestAttributeListener

MethodsDescription
void attributeAdded(ServletRequestAttributeEvent e)notification that a new attribute was added to the servlet request.
void attributeRemoved(ServletRequestAttributeEvent e)notification that an existing attribute was removed from the servlet request.
void attributeReplaced(ServletRequestAttributeEvent e)notification that an attribute was replaced on the servlet request

What is ServletContextAttributeEvent?

ServletContextAttributeEvent class let's you know if an attribute in a web application context has been added, removed or replaced.
Implementation of ServletContextAttributeListener interface, receive notifications of changes to the attribute list on the servlet context of a web application.

Some Important Methods of ServletContextAttributeListener

MethodsDescription
void attributeAdded(ServletContextAttributeEvent e)notification that a new attribute was added to the context.
void attributeRemoved(ServletContextAttributeEvent e)notification that an existing attribute was removed from the context.
void attributeReplaced(ServletContextAttributeEvent e)notification that an attribute was replaced on the context
Read More
Unknown

ServletContextEvent and ServletContextListener?

ServletContextEvent and ServletContextListener?

ServletContextEvent class gives notifications about changes to the servlet context of a web application. ServletContextListener receives the notifications about changes to the servlet context and perform some action. ServletContextListener is used to perform important task at the time when context is initialized and destroyed. In short, ServletContextEvent and ServletContextListener works in pair, whenever Servlet COntext changes, ServletContextEvent publishes a notification which is received by ServletContextListener and then, based on that certain tasks are performed by it.

Methods of ServletContextListener Interface

MethodsDescription
void contextDestroyed(ServletContextEvent e)is invoked when the application is destroyed.
void contextInitialized(ServletContextEvent e)is invoked when the application is initialized.

Making and Using a context listener

Context listener is not a servlet or JSP, it's a class that implements ServletContextListener interface and provides definition of contextDestroyed() and contextInitialized().
Using a ServletContextListener

Example demontrating usage of ServletContextListener


index.html
<a href="Counter">Total Page views</a>

web.xml
Using a ServletContextListener in web xml

For this example we will have to create a table named counter with a column named pageview to save the number of pageviews.
MyListener.java
import java.sql.*;
import javax.servlet.*;

public class MyListener implements ServletContextListener
{
    ServletContext ctx;
    Connection con;
    Statement s;
    PreparedStatement ps;
    ResultSet rs;
    int count;
    
    public void contextInitialized(ServletContextEvent sce) {
    
     try{
        Class.forName("com.mysql.jdbc.Driver");
       con= DriverManager.
               getConnection("jdbc:mysql://localhost:3306/test","user","password");

      s=con.createStatement();
      
      //fetching pageviews value from table counter
      rs=s.executeQuery("select pageview from counter");
        while(rs.next())
        {
            count=rs.getInt(1);
        }
       
       ctx=sce.getServletContext();
       ctx.setAttribute("pcount", count);
      }
      catch(Exception e){ e.printStackTrace(); }  
    }

    public void contextDestroyed(ServletContextEvent sce) {
   
     try
     {
       ctx=sce.getServletContext();
       count=(Integer)ctx.getAttribute("pcount");
       ps=con.prepareStatement("update counter set pcount='"+count+"'");
       ps.executeUpdate(); 
     } 
     catch(Exception e){ e.printStackTrace(); }
    }   
}

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

public class Counter extends HttpServlet {
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext ctx = getServletContext();
        Integer count = (Integer)ctx.getAttribute("pcount");
        out.println(count+": pageview");
        ctx.setAttribute("pcount", ++count);      
    }
}
Read More
Unknown

Using Hidden Form Field for Session Management

Using Hidden Form Field for Session Management

Hidden form field can also be used to store session information for a particular client. In case of hidden form field a hidden field is used to store client state. In this case user information is stored in hidden field value and retrieved from another servlet.

Advantages :

  • Does not have to depend on browser whether the cookie is disabled or not.
  • Inserting a simple HTML Input field of type hidden is required. Hence, its easier to implement.

Disadvantage :

  • Extra form submission is required on every page. This is a big overhead.

Example demonstrating usage of Hidden Form Field for Session

hidden form field
Below mentioned files are required for the example:

index.html
<form method="post" action="validate">
  Name:<input type="text" name="user" /><br/>
  Password:<input type="text" name="pass" ><br/>
  <input type="submit" value="submit">
</form>

web.xml
<web-app...>
    
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>Second</servlet-name>
        <servlet-class>Second</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Second</servlet-name>
        <url-pattern>/Second</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
</web-app>

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

public class First extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
 //getting value submitted in form from HTML file
        String user = request.getParameter("user");
        
        //creating a new hidden form field
        out.println("<form action='Second'>");
        out.println("<input type='hidden' name='user' value='"+user+"'>");
        out.println("<input type='submit' value='submit' >");
        out.println("</form>");
    }
}

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

public class Second extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //getting parameter from the hidden field
        String user = request.getParameter("user");
        out.println("Welcome "+user);
    }
}

Like we created a hidden field in First Servlet, populated the value of user, and sent it to the Second Servlet, now Second servlet also has the user information. Similarly we will have to keep sending this information, wherever we need this, using hidden fields.

Read More
Unknown

Using URL Rewriting for Session Management

Using URL Rewriting for Session Management

If the client has disabled cookies in the browser then session management using cookie wont work. In that case URL Rewriting can be used as a backup. URL rewriting will always work.
In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of name/value pair seperated by an equal(=) sign.
For Example:
using url rewriting for session management
When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of information at the end of URL. The Web Container will fetch the extra part of the requested URL and use it for session management.
The getParameter() method is used to get the parameter value at the server side.

Example demonstrating usage of URL rewriting

Below mentioned files are required for the example:

index.html
<form method="post" action="validate">
  Name:<input type="text" name="user" /><br/>
  Password:<input type="text" name="pass" ><br/>
  <input type="submit" value="submit">
</form>

web.xml
<web-app...>
    
    <servlet>
        <servlet-name>validate</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>validate</servlet-name>
        <url-pattern>/validate</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
</web-app>

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

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        if(pass.equals("1234"))
        {
            response.sendRedirect("First?user_name="+name+"");
        }
    }   
}

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

public class First extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String user = request.getParameter("user_name");
        out.println("Welcome "+user);
    }
}
Read More
Unknown

Using Cookies for Session Management

Using Cookies for Session Management

Cookies are small pieces of information that are sent in response from the web server to the client. Cookies are the simplest technique used for storing client state.
Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.
Using Cookies for storing client state has one shortcoming though, if the client has turned of COokie saving settings in his browser then, client state can never be saved because the browser will not allow the application to store cookies.

Cookies API

Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to response object.
session management using cookie

Example demonstrating usage of Cookies

cookies example
Below mentioned files are required for the example:

index.html
<form method="post" action="validate">
  Name:<input type="text" name="user" /><br/>
  Password:<input type="text" name="pass" ><br/>
  <input type="submit" value="submit">
</form>

web.xml
<web-app...>
    
    <servlet>
        <servlet-name>validate</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>validate</servlet-name>
        <url-pattern>/validate</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
</web-app>

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

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        if(pass.equals("1234"))
        {
            Cookie ck = new Cookie("username",name);
            response.addCookie(ck);
            response.sendRedirect("First");
        }
    }
}

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

public class First extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cks = request.getCookies();
        out.println("Welcome "+cks[0].getValue());
    }
}
Read More
Unknown

Managing Session in Servlets

Managing Session in Servlets

We all know that HTTP is a stateless protocol. All requests and responses are independent. But sometimes you need to keep track of client's activity across multiple requests. For eg. When a User logs into your website, not matter on which web page he visits after logging in, his credentials will be with the server, until he logs out. So this is managed by creating a session.
Session Management is a mechanism used by the Web container to store session information for a particular user. There are four different techniques used by Servlet application for session management. They are as follows:
  1. Cookies
  2. Hidden form field
  3. URL Rewriting
  4. HttpSession
Session is used to store everything that we can get from the client from all the requests the client makes.

How Session Works

session management in java

The basic concept behind session is, whenever a user starts using our application, we can save a unique identification information about him, in an object which is available throughout the application, until its destroyed. So wherever the user goes, we will always have his information and we can always manage which user is doing what. Whenever a user wants to exit from your application, destroy the object with his information.



Read More
Unknown

Introduction to Attribute

Introduction to Attribute

An attribute is an object that is used to share information in a web app. Attribute allows Servlets to share information among themselves. Attributes can be SET and GET from one of the following scopes :
  1. request
  2. session
  3. application
setting and getting an attribute

How to SET an Attribute

public void setAttribute(String name, Object obj) method is used to SET an Attribute.
Example demonstrating Setting Attribute
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc = getServletContext();
        sc.setAttribute("user","Abhijit"); //setting attribute on context scope
    }
}

How to GET an Attribute

Object getAttribute(String name) method is used to GET an attribute.
Example demonstrating getting a value of set Attribute
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Second extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc = getServletContext();
 
        String str = sc.getAttribute("user");  //getting attribute from context scope
 
        out.println("Welcome"+str);  // Prints : Welcome Abhijit   
    }
}
Read More
Unknown

Introduction to ServletContext Interface

Introduction to ServletContext Interface

For every Web application a ServletContext object is created by the web container. ServletContext object is used to get configuration information from Deployment Descriptor(web.xml) which will be available to any servlet or JSPs that are part of the web app.

Some Important method of ServletContext

MethodsDescription
Object getAttribute(String name)returns the container attribute with the given name, or NULL if there is no attribute by that name.
String getInitParameter(String name)returns parameter value for the specified parameter name, or NULL if the parameter does not exist
Enumeration getInitParameterNames()returns the names of the context's initialization parameters as an Enumeration of String objects
void setAttribute(String name,Object obj)set an object with the given attribute name in the application scope
void removeAttribute(String name)removes the attribute with the specified name from the application context

How Context Parameter is Initialized inside web.xml

how to initialize servlet context using deployment descriptor

How to get the Object of ServletContext

ServletContext app = getServletContext();
OR
ServletContext app = getServletConfig().getServletContext();

Advantages of ServletContext

  • Provides communication between servlets
  • Available to all servlets and JSPs that are part of the web app
  • Used to get configuration information from web.xml

Difference between Context Init Parameters and Servlet Init Parameter

Context Init parametersServlet Init parameter
Available to all servlets and JSPs that are part of webAvailable to only servlet for which the <init-param> was configured
Context Init parameters are initialized within the <web-app> not within a specific <servlet> elementsInitialized within the <servlet> for each specific servlet.
ServletContext object is used to get Context Init parametersServletConfig object is used to get Servlet Init parameters
Only one ServletContext object for entire web appEach servlet has its own ServletConfig object

Example demonstrating usage of ServletContext

web.xml
<web-app ...>

   <context-param>
       <param-name>driverName</param-name>
       <param-value>sun.jdbc.JdbcOdbcDriver</param-value>
   </context-param>
   
   <servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>MyServlet</servlet-class>
   </servlet>
   
   <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
   </servlet-mapping> 
     
</web-app>
MyServlet class :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

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();
        ServletContext sc = getServletContext();
        out.println(sc.getInitParameter("driverName"));   
    }
}

Read More