How to implement a filter that redirects user to login page when session expires
A tutorial on how to implement a filter that redirects user in the login page when session expires
In this tutorial we will present you a way to implement a quite simple filter that will redirect users to login page.This a quite useful filter since there are web applications where users are doing something when session expires and must re-login in order to complete what they were doing.The below snippet is quite descriptive:
public class RedirectFilter implements Filter{
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
//check if "role" attribute is null
if(req.getSession().getAttribute("role")==null){
//forward request to login.jsp
req.getRequestDispatcher("/login.jsp").forward(request, response);
}else{
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
The key part in RedirectFilter class is the doFilter() method,where the filter checks if the role attribute is null or not and if it is null it forwards request to login page.All we have to do now is configure filter with inserting the below xml snipppet in the web.xml
<filter>
<filter-name>SoutPrinter</filter-name>
<filter-class>com.javaonly.filters.RedirectFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SoutPrinter</filter-name>
<url-pattern>/somepage.jsp</url-pattern>
</filter-mapping>
Copyright © 2012 Design and Development Nikos Lianeris

- 72

- 3




