Category Archives: Servlets

Filters

  • Filters are java components that can be used to process or intercept request from client to server before the request is sent to filter or to process responses after the servlet has completed its job and before this response reaches the client.
  • Deployment descriptor defines when to kick in filters.
  • Filters implement the Filter java interface.
  • Filters when used to intercept request can perform security checks, reformat request headers or bodies and can audit or log requests
  • Filters when used to process responses can compress the response stream, alter the response stream and can create a different response stream together.
  • Filters can also be chained together. Deployment descriptor will define the order in which they run.
  • Filters have a doFilter() method that the implementing class overwrites.
  • The container manages the life cycle of the filter. In many ways, Filter is like Servlet in characteristic.
  • Every filter can have access to ServletContext from its FilterConfig Object.

Filter’s Life Cycle:

  • Every filter must implement init(), do Filter() and destroy() methods.
  • Init(): This is where you do any set up tasks. The most common implementation is as follows

Public void init(FilterConfig config) throws ServletException{

// you can store config object of type FilterConfig in a variable to use it     //latter.you will get the servlet context from this config object

}

  • doFilter(): This is the method that gets called when ever the container determines that the filter should be applied to cureent request or response. It takes three arguments. They are ServletRequest, a ServletResponse and a FilterChain.This is where you implement your filter functionality.
  • Destroy(): called when the container decides to remove the instance. You can do any clean up work here.

How to Declare and order Filters?

Declaring a filter

<filter>

<filter-name>myFilter</filter-name>

<filter-class>com.mydomain.MyFilter</filter-class>

<init-param>

<param-name>user</param-name>

<param-value>sukumarvaddi</param-value>

</init-param>

</filter>

Declaring a filter mapping to a URL pattern

<filter-mapping>

<filterName>myFilter</filterName>

<url-pattern>*.do</url-pattern>

</filter-mapping>

Declaring a filter mapping to a servlet name

<filter-mapping>

<filter-name>myFilter<filter-name>

<servlet-name>com.myDomain.MyServlet</servlet-name>

</filter-mapping>

Advertisements

Session management

  • Http protocol makes use of stateless connections for scalability. That means the server cannot remember clients between requests.
  • In J2EE World, the servlet container generates a unique session ID on client’s request and gives it back to client along with the response. The client sends that sessionID with each subsequent request. The container identifies the client by seeing the sessionID, finds the matching session and associates the session with the request.
  • The client and container exchange the session information through cookies. The container sends a “set-cookie” header in the response. When the client makes subsequent request, it sends “Cookie” header in the request.
  • The container handles all the cookie work and you as a developer do not need to worry about it. The only thing you as a developer need to worry about is to tell the container that you want to create or use a session. The container handles the rest of the work like creating session ID, creating a new cookie, stuffing the sessionID  into the cookie and setting the cookie as part of the response header.

How do you send the session Cookie in a RESPONSE?

HttpSession session = request.getSession():

As soon as you say this in your service method, every thing happens automatically for you. The above code does just more than creating a session. When you invoke it the first time, it will send a cookie in the response. You do not do any of the following

  • Do not make the new HttpSession object.
  • do not generate unique session ID.
  • Do not make a new cookie Object
  • Do not stuff the sessionID into the cookie Object
  • Do not set the cookie into the response.

How do you get the Session ID from the REQUEST?

HttpSession session = request.getSession();

If the received request has a session ID cookie, the container finds the matching session using the included session ID. Otherwise, it will create a new session.

How do you know if there was a session already?

You use the function of the session as syntaxed below

session.isNew();

This method returns “true” if the container cannot find a session ID or matching session ID in the request.

Overloaded getSession method

There is another overload method called request.getSession(boolean). If you set the parameter of this method to false, you will either get a null or a pre-existing session. If the method runs null, you can create a new session if you want.

Passing Boolean value true to that method is same as request.getSession() described in the above parts of this blog.

URL Rewriting to make sessions work

If the cookies are disabled in the browser, the above mentioned methods will not work as the client will never join the session implying that the session.isNew() method always return true. In this situation, you can use URL rewriting.

In URL rewriting, the sessionID that is otherwise stuff with in the cookie , is now appended to the end of the URL that comes into this app.

The container always uses cookie approach first and if it fails, it uses URL rewriting to accomplish sessions.  Container accomplishes URL rewriting only if you as a developer have done the job of encoding all the URLs you send in the response. The syntax for it is

response.encodeURL(“/myServlet.do”).

By encoding as mentioned above, the container adds extra session ID info to the above URL. You can also redirect the request to different URL , but want to use the same session, you can use response.encodeRedirectURL(“/myServlet.do”).

Important points to remember:

  • You can use URL rewriting only if all the pages that are part of the session are dynamically generated.
  • URL rewriting is done in a vendor specific way. Tomcat us a semicolon to append session ID to the URL.
  • URLRewriting is handled by response object.

Important methods of HttpSession:

  • getCreationTime(): returns the session creation time.
  • getLastAccessedTime(): returns the last time the container got a request  with this session ID
  • setMaxInactiveInterval(): Maximum time in seconds allowed between requests in the session
  • getMaxInactiveInterval(): returns maximum time  in seconds that is allowed between requests for this session
  • invalidate(): Concludes the session. Unbinds all the session attributes currently in the session

How do you set session time out?

The container gets rid of all the pale sessions. The session can die because of time out or call to invalidate() on the session or the  browser or computer crashes.

Open web.xmal and paste the following to make session die after 15 minutes of being idle

<web-app>

<session-config>

<session-timeout>15</session-timeout>

</session-config>

</web-app>

You can also set session time out for a specific session with out effecting the time out length for any other session in the web application using session.setMaxInactiveInterval(15*60);

Other uses of cookies:

  • Cookies can be used to exchange name/value pairs between client and server. The server sends the cookie to the client and the client in turn will send the cookie back to server with each subsequent request.  Session cookies are vanished when the client browser quits. There is a way to tell the cookie to persist on the client even after the browser shuts down. Using this way, the web application can still get the cookie information even though the session with client was expire long back

Getting Cookie Information using Servlet API:

  • You can get all the information you need to know about cookies using HttpServletRequest, HttpServletResponse and Cookie classes of Servlet API

Cookie Code:

  • Creating a new cookie

Cookie cookie = new Cookie(“userName”, name);

  • Sending the cookie to the client

response.addCookie(cookie);

  • Setting how long acookie will live on the client

Cookie.setMaxAge(time in seconds).

Setting max age to -1 makes the cookie disappear when the browser closes.

  • Getting cookie form the client request

Cookie[] cookie = request.getCookies();

For(int i=0;i<cookie.length; i++){

Cookie cookie = cookie[i];

If(cookie.getName().equals(“userName”)){

String username= cookie.getValue();

Out.println(username);

Break;

}

}

Some points worth knowing regarding HTTP Session

  • You do not configure HttpSessionBindingListner in deployment descriptor as it is not related to session on whole. It is to let the object used as attribute to know if it is bound or unbound to session. The object should implement HttpSessionBindingListener.
  • In a distributed application there may be multiple JVMs’ which may or may not be on same physical servers and so the app is in multiple places. So during load balancing, the same client requests could end up going to different instances of the same servlet. In such situations, the following things happen to ServletContext, ServletConfig and HttpSession.

ServletContext:There are multiple contexts @ one context per VM

ServletConfig: There are multiple configs as well @ one ServletConfig perServlet per VM

HttpSessionObject: Only one HttpSession on all the VMs’ combined. HttpSessions along with their attributes move from one VM to another

  • Servlet specs do not dictate the container vendor to support clustering. How an app server handles clustering is completely at the mercy of the vendor.
  • Sessions upon migrating from one VM to other do not leave its trace. It is passivated on the VM it existed before moving to another VM in which it is activated. There is a slight delay or latency using this process.
  • HttpSessionActivationListener prepares attributes to move from one VM to another which means the attributes should ready their instance variables for serialization.
  • If some of the attribute instance variables are not serializable, use  activation/passivation call back methods to prepare them for serialization so that the state exists as it used to be in the previous VM before migrating to the new VM. (user writeObject () and readObject() methods)
  • HttpSessionEvent has getSession method to get the current session where as HttpSessionBindingEvent has getName() which returns name of the attribute, getValue() which returns the object in addition to getSession method.

Various Listener interfaces and their methods and Event types in a web application

ServletContextListener: wrote a whole blog about it.

Methods: ContextInitialized(ServletContextEvent event)

ContextDestroyed(ServletContextEvent event)

ServletContextAttributeListener:  Notifies if an attribute has been added, removed or replaced to a web application context.

Methods: attributeAdded(ServletContextAttributeEvent event)

attributeRemoved(ServletContextAttributeEvent event)

attributeReplaced(ServletContextAttributeEvent event)

HttpSessionListener: To track active sessions in the application.

Methods: sessionCreated(HttpSessionEvent event);

sessionDestroyed(HttpSessionEvent event);

ServletRequestListener: Notifies about the arrival of request.

Methods: requestInitialized(ServletRequestEvent event);

requestDestroyed(ServletRequestEvent event);

ServletRequestAttributeListener: Notifies if a request attribute has been added, removed or replaced.

Methods: attributeAdded(ServletRequestAttributeEvent event)

attributeRemoved(ServletRequestAttributeEvent event)

attributeReplaced(ServletRequestAttributeEvent event)

HttpSessionBindingListener: Notifies the Objects of the class when these objects have been bound (set as attributes using session.setAttribute(string, object)) to or removed (removed using seesion.removeAttribute(string))from a session.

Methods:valueBound(HttpSessionBindingEvent event)

valueUnbound (HttpSessionBindingEvent event)

HttpSessionAttributeListeners: Notifies if a session attribute has been added, removed or replaced.

Methods: attributeAdded(HttpSessionBindingEvent  event)

attributeRemoved(HttpSessionBindingEvent event)

attributeReplaced(HttpSessionBindingEvent  event)

HttpSessionActivationListener: Notifies the objects of the class when the session to which they are bound migrates from one JVM to another in a clustered environment.

Methods: sessionDidActivate(HttpSession Event event);

sessionWillPassivate(HttpSessionEvent event);

ServletContextListener

  • ServletContextListener initializes the web application. It is some thing that sits in the Container to be notified of the events during the start of web application. It kicks in before any of the servlet or JSP is instantiated. ServletContextListener is instantiated after the servletContext is created and before any of the servlet or JSP is instantiated. Refer to page 178  of “Head First Servlets and JSP”
  • Useful in init parameter lookup for creating database connections. It will store database connection as an attribute of the ServletContext. All parts of the web application can access it. All this stuff is done in              public void contextInitialized(ServletContextEvent event) function of the ServletContextListener.
  • Can also perform house keeping functions such as database connection close up before the web application demises. Typically this is performed in  public void contextDestroyed(ServletContextEvent event) function of the ServletContextListener.                                                                                                                                                      Follow the following steps to listen for servletContextEvents(application is being deployed)
  • Write a listener Class that implements ServletContextListener
    public class MyServletContextListener implements ServletContextListener
  • Put that in WEB-INF/classes directory.
  • define this to the container in the deployment descriptor web.xml as shown below
    <listener>
    <listener-class>
    com.mylistener.MyServletContextListener
    </listener-class>
    </listener>

  • To implement ServletContextListener, the class you define should implement two  methods. One of them is public void contextInitialized(ServletContextEvent event).This method is executed when the application is being deployed. You get ServletContext  from ServletContextEvent  using the code  event.getServletContext(); The second method is                                                                                                               public void contextDestroyed(ServletContextEvent event). This method is executed when the application is about to shutdown.

Differences Between ServletContext and ServletConfig

ServletContext:

  1. You have only one ServletContext per web application
  2. Your Deployment Descriptor (web.xml) looks like the following when you specify context init parameters.

<web-app ……>

<context-param>

<param-name>myName</param-name>

<param-value>sukumar vaddi</param-value>

<context-parm>

</web-app>

  1. 3. You read the context parameters in the servlet using the code  getServletContext().getInitParameter(“myName”);
  2. This is available to all the servlets and JSPs that make up the web application.

ServletConfig:

  1. You have one servletConfig per servlet.
  2. Your Deployment Descriptor (web.xml) looks like the following when you specify servlet init parameters.

<web-app ……>

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>myDomain.ServletInit</servlet-class>

</servlet>

<int-param>

<param-name>myName</param-name>

<param-value>sukumar vaddi</param-value>

<init-parm>

</web-app>

  1. 3. You read the servlet init parameters in the servlet using the code getServletConfig().getInitParameter(“myName”);
  2. 4. ServletConfig is available to only the servlet for which <init-param> was defined. But it can be made widely avialbe by storing it as an attribute.

Source: Head First Servlets and JSP