Saturday, July 28, 2018

Example of FilterConfig

In this example, if you change the param-value to no, request will be forwarded to the servlet otherwise filter will create the response with the message: this page is underconstruction.
  1. index.html
  2. MyFilter.java
  3. HelloServlet.java
  4. web.xml
index.html

<a href="servlet1">click here</a>

MyFilter.java

import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.*; 
 
public class MyFilter implements Filter{ 
FilterConfig config; 
 
public void init(FilterConfig config) throws ServletException { 
    this.config=config; 

 
public void doFilter(ServletRequest req, ServletResponse resp, 
    FilterChain chain) throws IOException, ServletException { 
     
    PrintWriter out=resp.getWriter(); 
         
    String s=config.getInitParameter("construction"); 
         
    if(s.equals("yes")){ 
         out.print("This page is under construction"); 
    } 
    else{ 
         chain.doFilter(req, resp);//sends request to next resource 
    } 
         

public void destroy() {} 
}   


HelloServlet.java

import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.*; 
 
public class HelloServlet extends HttpServlet { 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException { 
 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
     
        out.print("<br>welcome to servlet<br>"); 
         
    } 
 
}


web.xml

<web-app> 
 
 <servlet> 
    <servlet-name>HelloServlet</servlet-name> 
    <servlet-class>HelloServlet</servlet-class> 
  </servlet> 
 
  <servlet-mapping> 
    <servlet-name>HelloServlet</servlet-name> 
    <url-pattern>/servlet1</url-pattern> 
  </servlet-mapping> 
   
  <filter> 
  <filter-name>f1</filter-name> 
  <filter-class>MyFilter</filter-class> 
  <init-param> 
  <param-name>construction</param-name> 
  <param-value>no</param-value> 
  </init-param> 
  </filter> 
  <filter-mapping> 
  <filter-name>f1</filter-name> 
  <url-pattern>/servlet1</url-pattern> 
  </filter-mapping> 
   
   
</web-app>

Simple Example of Filter

  1. index.html
  2. MyFilter.java
  3.  HelloServlet.java
  4. web.xml
index.html

<a href="servlet1">click here</a>

MyFilter.java

import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.*; 
 
public class MyFilter implements Filter{ 
 
public void init(FilterConfig arg0) throws ServletException {} 
     
public void doFilter(ServletRequest req, ServletResponse resp, 
    FilterChain chain) throws IOException, ServletException { 
         
    PrintWriter out=resp.getWriter(); 
    out.print("filter is invoked before"); 
         
    chain.doFilter(req, resp);//sends request to next resource 
         
    out.print("filter is invoked after"); 
    } 
    public void destroy() {} 


HelloServlet.java

import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.*; 
 
public class HelloServlet extends HttpServlet { 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
     
        out.print("<br>welcome to servlet<br>"); 
         
    } 
 


web.xml

<web-app> 
 
<servlet> 
<servlet-name>s1</servlet-name> 
<servlet-class>HelloServlet</servlet-class> 
</servlet> 
 
<servlet-mapping> 
<servlet-name>s1</servlet-name> 
<url-pattern>/servlet1</url-pattern> 
</servlet-mapping> 
 
<filter> 
<filter-name>f1</filter-name> 
<filter-class>MyFilter</filter-class> 
</filter> 
  
<filter-mapping> 
<filter-name>f1</filter-name> 
<url-pattern>/servlet1</url-pattern> 
</filter-mapping> 
 
 
</web-app>

Servlet Filter

  • A filter is an object that is invoked at the preprocessing and postprocessing of a request.
  • It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.
  • The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet.
  • So maintenance cost will be less.
Advantage of Filter
  1. Filter is pluggable.
  2. One filter don't have dependency onto another resource.
  3. Less Maintenance
Filter API
The javax.servlet package contains the three interfaces of Filter API.
  1. Filter
  2. FilterChain
  3. FilterConfig
Filter interface

For creating any filter, you must implement the Filter interface. Filter interface provides the life cycle methods for a filter.


Method
Description
public void init(FilterConfig config)
init() method is invoked only once. It is used to initialize the filter.
public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)
doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
public void destroy()
This is invoked only once when filter is taken out of the service.












FilterChain interface

The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only one method:
  1. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control to the next filter or resource.
FilterConfig interface

An object of FilterConfig is created by the web container. This object can be used to get the configuration information from the web.xml file.

Methods of FilterConfig interface

There are following 4 methods in the FilterConfig interface.
  1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  2. public String getInitParameter(String parameterName): Returns the parameter value for the specified parameter name.
  3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter names.
  4. public ServletContext getServletContext(): Returns the ServletContext object.
How to define Filter

We can define filter same as servlet. Let's see the elements of filter and filter-mapping.


<web-app> 
 
<filter> 
<filter-name>...</filter-name> 
<filter-class>...</filter-class> 
</filter> 
  
<filter-mapping> 
<filter-name>...</filter-name> 
<url-pattern>...</url-pattern> 
</filter-mapping> 
 
</web-app>

Monday, July 9, 2018

HttpSessionActivationListener

Methods of HttpSessionActivationListener interface
  1. public void sessionWillPassivate(HttpSessionEvent se): Notification that the session is about to be passivated.
  2. public void sessionDidActivate(HttpSessionEvent se): Notification that the session has just been activated.

HttpSessionAttributeListener

Methods of HttpSessionAttributeListener interface
  1. void attributeAdded(HttpSessionBindingEvent event): Receives notification that an attribute has been added to a session.
  2.  void attributeRemoved(HttpSessionBindingEvent event): Receives notification that an attribute has been removed from a session.
  3. void attributeReplaced(HttpSessionBindingEvent event): Receives notification that an attribute has been replaced in a session.

HttpSessionBindingEvent and HttpSessionBindingListener


Constructor of  HttpSessionBindingEvent class
  1. public HttpSessionBindingEvent(HttpSession session, java.lang.String name)
  2. public HttpSessionBindingEvent(HttpSession session, java.lang.String name, java.lang.Object value): Constructs an event that notifies an object that it has been bound to or unbound from a session
Methods of  HttpSessionBindingEvent class
  1. public HttpSession getSession(): Return the session that changed.
  2. public java.lang.String getName(): Returns the name with which the attribute is bound to or unbound from the session.
  3. public java.lang.Object getValue(): Returns the value of the attribute that has been added, removed or replaced. If the attribute was added (or bound), this is the value of the attribute. If the attribute was removed (or unbound), this is the value of the removed attribute. If the attribute was replaced, this is the old value of the attribute.
Methods of  HttpSessionBindingListener interface
  1. void valueBound(HttpSessionBindingEvent event): Notifies the object that it is being bound to a session and identifies the session.
  2. void valueUnbound(HttpSessionBindingEvent event): Notifies the object that it is being unbound from a session and identifies the session.

HttpSessionEvent and HttpSessionListener


  • The HttpSessionEvent is notified when session object is changed. The corresponding Listener interface for this event is HttpSessionListener.
  • We can perform some operations at this event such as counting total and current logged-in users, maintaing a log of user details such as login time, logout time etc.
Constructor of HttpSessionEvent class
  1. HttpSessionEvent(HttpSession source): Construct a session event from the given source.
Method of HttpSessionEvent class
  1. public HttpSession getSession(): Return the session that changed
Methods of HttpSessionListener interface
  1. public void sessionCreated(HttpSessionEvent e): is invoked when session object is created.
  2. public void sessionDestroyed(ServletContextEvent e): is invoked when session is invalidated. 
In this example, are counting the total and current logged-in users. For this purpose, we have created three files:

    Login.html: to get input from the user.
    MyListener.java: A listener class that counts total and current logged-in users and stores this    
    information in ServletContext object as an attribute.
    First.java: A Servlet class that creates session and prints the total and current logged-in users.
    Logout.java: A Servlet class that invalidates session.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
  <listener>
  <listener-class>CountUserListener</listener-class>
  </listener>
 
  <servlet>
     <servlet-name>First</servlet-name>
    <servlet-class>First</servlet-class>
  </servlet>
  <servlet>
      <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>LogoutServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>First</servlet-name>
    <url-pattern>/servlet1</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/logout</url-pattern>
  </servlet-mapping>
 
</web-app>


CountUserListener.java

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

public class CountUserListener implements HttpSessionListener{
    ServletContext ctx=null;
    static int total=0,current=0;
   
    public void sessionCreated(HttpSessionEvent e) {
    total++;
    current++;
   
    ctx=e.getSession().getServletContext();
    ctx.setAttribute("totalusers", total);
    ctx.setAttribute("currentusers", current);
   
    }

    public void sessionDestroyed(HttpSessionEvent e) {
            current--;
            ctx.setAttribute("currentusers",current);
    }

}

Login.html


<form action="servlet1">
Name:<input type="text" name="username"><br>
Password:<input type="password" name="userpass"><br>

<input type="submit" value="login"/>
</form>


First .java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 First extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
   
        String n=request.getParameter("username");
        out.print("Welcome "+n);
      
        HttpSession session=request.getSession();
        session.setAttribute("uname",n);
      
        ServletContext ctx=getServletContext();
        int t=(Integer)ctx.getAttribute("totalusers");
        int c=(Integer)ctx.getAttribute("currentusers");
        out.print("<br>total users= "+t);
        out.print("<br>current users= "+c);
        out.print("<br><a href='logout'>logout</a>");
        out.close();
    }

}


LogoutServlet .java

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 LogoutServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
   
        HttpSession session=request.getSession(false);
        session.invalidate();
      
        out.print("You are successfully logged out");
        out.close();
    }

}

ServletContextAttributeEvent and ServletContextAttributeListener

Constructor of ServletContextAttributeEvent Class
  1. public ServletContextAttributeEvent(ServletContext source, java.lang.String name,java.lang.Object value): Construct a ServletContextAttributeEvent from the given context for the given attribute name and attribute value.
Methods of ServletContextAttributeEvent Class
  1. public java.lang.String getName(): Return the name of the attribute that changed on the ServletContext.
  2. public java.lang.Object getValue(): Returns the value of the attribute that has been added, removed, or replaced.
Methods of  ServletContextAttributeListener interface
  1. void attributeAdded(ServletContextAttributeEvent event): Receives notification that an attribute has been added to the ServletContext.
  2. void attributeRemoved(ServletContextAttributeEvent event): Receives notification that an attribute has been removed from the ServletContext.
  3. void attributeReplaced(ServletContextAttributeEvent event): Receives notification that an attribute has been replaced from the ServletContext.

ServletRequestAttributeEvent and ServletRequestAttributeListener

Constructor of ServletRequestAttributeEvent 
  1. public ServletRequestAttributeEvent(ServletContext sc, ServletRequest request, java.lang.String name, java.lang.Object value)

Parameters:
    sc - the ServletContext that is sending the event.
    request - the ServletRequest that is sending the event.
    name - the name of the request attribute.
    value - the value of the request attribute.

Methods of ServletRequestAttributeEvent
  1. public java.lang.String getName(): Return the name of the attribute that changed on the ServletRequest. 
  2. public java.lang.Object getValue(): Returns the value of the attribute that has been added, removed or replaced.
Methods of ServletRequestAttributeListener
  1. void attributeAdded(ServletRequestAttributeEvent srae): Receives notification that an attribute has been added to the ServletRequest.
  2. void attributeRemoved(ServletRequestAttributeEvent srae): Receives notification that an attribute has been removed from the ServletRequest.
  3. void attributeReplaced(ServletRequestAttributeEvent srae): Receives notification that an attribute has been replaced on the ServletRequest.

ServletContextEvent and ServletContextListener


  • The ServletContextEvent is notified when web application is deployed on the server.
  • If you want to perform some action at the time of deploying the web application such as creating database connection, creating all the tables of the project etc, you need to implement ServletContextListener interface and provide the implementation of its methods. 

Constructor of ServletContextEvent class
  1. ServletContextEvent(ServletContext source): Construct a ServletRequestEvent for the given ServletContext and ServletRequest.

Methods of ServletContextEvent class
  1.  public ServletContext getServletContext(): Returns the instance of ServletContext.
Methods of ServletContextListener interface
  1. public void contextInitialized(ServletContextEvent e): is invoked when application is deployed on the server.
  2. public void contextDestroyed(ServletContextEvent e): is invoked when application is undeployed from the server.

ServletRequestEvent and ServletRequestListener


Constructor of ServletRequestEvent Class
  1. public ServletRequestEvent(ServletContext sc, ServletRequest request) 
Methods of ServletRequestEvent Class
  1. public ServletRequest getServletRequest(): Returns the ServletRequest that is changing. 
  2. public ServletContext getServletContext(): Returns the ServletContext of this web application.
 Methods of ServletRequestListener
  1. void requestDestroyed(ServletRequestEvent sre): Receives notification that a ServletRequest is about to go out of scope of the web application.
  2. void requestInitialized(ServletRequestEvent sre): Receives notification that a ServletRequest is about to come into scope of the web application.


Event and Listener in Servlet

Servlet Listener is used for listening to events in a web containers, such as when you create a session, or place an attribute in an session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml.

Event classes
  1. ServletRequestEvent
  2. ServletContextEvent
  3. ServletRequestAttributeEvent
  4. ServletContextAttributeEvent
  5. HttpSessionEvent
  6. HttpSessionBindingEvent
Event interfaces
  1. ServletRequestListener
  2. ServletContextListener
  3. ServletRequestAttributeListener
  4. ServletContextAttributeListener
  5. HttpSessionListener
  6. HttpSessionBindingListener
  7. HttpSessionAttributeListener
  8. HttpSessionActivationListener 

Thursday, July 5, 2018

HttpSession interface

  • Container creates a session id for each user.
  • The container uses this id to identify the particular user.

An object of HttpSession can be used to perform two tasks:
  1. bind objects
  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
Get the HttpSession object:

The HttpServletRequest interface provides two methods to get the object of HttpSession:


1. public HttpSession getSession(): 
  • If the session already exist, it will return existing session else create a new session
2. public HttpSession getSession(boolean create):
  •  If create is true, Always returns a new session.
  • If create is false returns a existing session.

Commonly used methods of HttpSession interface:


  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it
Creating a New Session

HttpSession session = request.getSession();  // If the session already exist, 
                                                                           it will return existing  session else create a new session
HttpSession session = request.getSession(true); //Always returns a new session
session.setAttribute("uname","Bharath");
        
Getting Existing Session

HttpSession session = request.getSession(false);  //Always returns existing session
String name = (String)session.getAttribute("uname");  

Destroying a Session

session.invalidate();