Following small piece of code comes handy whenever you are working for a J2EE web application in JSP/Servlet/Struts/JSF or any Servlet oriented web framework.
A lot of time we have to handle session errors in such applications and redirect user to particular error page. Generally user is redirected to the login page where she can giver her credential and log in the application again.
In my previous post, I wrote about handling session errors and other server errors at client side using AJAX. But for doing this still we have to handle the session errors first at server side.
Let us see how we can track user session using Servlet Filter and redirect her to login page if session is already invalidated. We will induce session tracking facility to our web project (for this tutorial, I am using normal JSP web application in Eclipse).
Step 1: Create Servlet Filter to track Session
Create a package to place our session filter (in this case net.viralpatel.servlet.filter) and create a Java class SessionFilter.
Copy following code in the Java file.
The init() method will get called by the servlet container and will get FilterConfig object as arguement. From this config object, we read the init parameters. We will see shortly what parameters do we passed in filter.
The doFilter() method will be called for each request of our application. Hence we can check the session in this method and see if it is valid. From init() method, we had generated a list of pages (urls) that were having access although the session is null. Index pages, error pages and other pages that you think user can access without logging in should be specified in this list.
In doFilter() method, you will notice one response.sendRedirect. I have redirected my user to index.jsp page if session is not valid. You can give any landing URL that you want your user to go when session is not valid. Alternatively you may want to create a JSON response and send it to client if you think the request was originated from AJAX.
Step 2: Specify filter entry in Web.xml deployment descriptor
Copy following entry in your application’s Web.xml file.
We have specified the filter in web.xml file which will get called for url /*. You can configure the URL mapping like normal filters URL mapping. Also note that we have specified a parameter avoid-url in init-parameters of filter. The value of this parameter will be a comma separated paths that we do not want to apply session validations on. I have specified index.jsp, you can give more urls separated by comma.
index.jsp, someAction.do, Request.jsp, Message.jsf