Category Archives: Java


  • 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     // 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









Declaring a filter mapping to a URL pattern





Declaring a filter mapping to a servlet name






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


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


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(“/”).

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






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


  • 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];


String username= cookie.getValue();





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 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

  • 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


  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 ……>



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



  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.


  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 ……>







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



  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

java Web Application Security

  1. Impersonators, upgraders and Eavesdroppers are the main bad guys a web application developer needs to worry about.
  2. As per the servlet specification, the security of web application is about authentication, authorization, confidentiality and data integrity.
  3. Security is to be kept out of the code to support component-based development.
  4. Servlet specification does not mention anything about how the container should implement support for authenticating data. Usually, the container vendor will support a vendor-specific table containing usernames, passwords and roles. Vendors also provide a way to hook your application to the company specific authentication data in a LDAP System or relational database. The data in LDAP or relational database respective to security is maintained by administrator.

What does Realm means with respect to security?

Realm is nothing but a place where authentication information is stored. In tomcat it is tomcat-users.xml which is located in <tomcat installation directory>/conf/. It is known as memory realm. Not recommended for production.

How to enable authenticaton?

Add the following code in  deployment descriptor(web.xml)




There are four types of authentications. They differ in how securely the username and password info is transmitted.

  • BASIC: Transmits login info in an encoded form. Provides very weak security.
  • DIGEST: Transmits login info in a more secure way. As encryption is not widely used, you cannot trust J2EE containers to support this feature.
  • CLINET-CERT: Transmits login info in an extremely secure form, using public key certificates (PKC). Clients need to have certificate before they can login. Used mainly in business-business scenarios.
  • FORM: You can create custom login form in HTML. Login Info is transmitted in a least secure way among all the four as username and password are transmitted in the HTTP with no encryption. Turn on SSL or session Tracking, or the container might not recognize the login form when it is returned.

Configuration for form based authentication.








Inside the login.html page

<form method=”post” action=”j_security_check”>

<input  type=”text” name=”j_username”>

<input type=”password” name=”j_password”>

<input type=”submit”     value=”Enter”>


Inside loginError.html

<html><body>Wrong User Name and password</body</html>

How to define roles?

Add the following code in deployment descriptor(web.xml)




The role names has to match what is defined in the tomcat-users.xml

How to define resource/method constraints?

Add the following code in  deployment descriptor(web.xml)



<!–   Mandatory name used by tools. You do not see this name any where else–>


<!– Defines the resources to be constrained –>



<!– Describes which HTTP methods are constrained for the resources defined by  the url –>



<!–lists who is allowd to do  GET and POST on the specified URL pattern –>






You must specify at least one <url-pattern>

If no HTTP methods are specified then all methods will be constrained. This means that the resources can be accessed only by the roles in <auth-constraint>

You can have more than one <web-resource-collection> element. The <auth-constraint> element applies to  all <web-resource-collection> element in the <security-constraint>

If an <auth-constraint> element exists with no<role-name> element, then no users are allowed.

<role-name>*</role-name> specification allows all users. Role names are case sensitive.

<security- constraint> element is optional.

If an <auth-constraint> exists, the container must perform authentication for the associated URLs.

If an <auth-constraints> does not exist, the container must allow unauthenticated access to URLs.

Three HTTP request methods that are associated with programmatic security are

  • getUserPrincipal().
  • getRemoteUser().
  • isUserInRole().

To Link role in the programmatic security request function isUserRole(roleName) to what is specified in the  <role-name> see the following declaration in deployment descriptor

In Code:






In Deployment Descriptor (web.xml)

<web-app …>











Implementing data confidentiality and Integrity

  • use <security-constraint> to define data confidentiality and integrity.

Add the following in the deployment descriptor <security-constraint> element




The following are the valid values for <transport-guarantee>

  1. NONE (default): No data protection.
  2. INTEGRAL: Data must not be changed along the way.
  3. CONFIDENTIAL:  Data must not be seen by any bone along the transmission.

Every container virtually uses SSL for transport. So, Integral or confidential does the same thing.

Source: Head First Servlets and JSP

Database Connection Pooling in Tomcat

1. Open context.xml file, either in <tomcat installation directory>/conf or in META-INF folder of the web application for which you want to enable database connection pooling. If you do not have one in META-INF directory, create one and copy the contents of the context.xml in <tomcat installation directory>/conf.

2. Copy the following and paste with in the <context> element.  I have it for oracle10g database. You can modify it to suit your database. The following configuration takes care of resource leaks when you forget closing connections or result sets or so.

Connection Pooling will not work for databases with out password.

<Resource name=“Jdbc/myDB”




url=your database Connection URL

username=database user name

password=database password maxActive=“20” maxIdle=“10”




3.  Copy the following and paste it in web.xml of your

web application


<description>My connection Pooling</description>





4.  Code some thing like following to get the Connection

public Connection getMyDBConnection() {

Connection connection =null;


Context initCTX = new InitialContext();

Context envCtx = (Context) initCTX.lookup(“Jdbc/myDB “);

DataSource ds = (DataSource)envCtx.lookup(“Jdbc/QCToolDB”);

connection = ds.getConnection();

}catch(Exception e){



return connection;