Posted by: Rajaganesh Vanarajan on: November 6, 2008
This post is aimed at helping some small web application developers to secure their resources from unauthorized access. Just write a filter like this,
public class AuthenticationFilter implements Filter {
private FilterConfig config = null;
public void init(FilterConfig config) throws
ServletException {this.config = config;
}
public void destroy() {
config = null;
}
/*
* FILTER METHOD
*/
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
/*
*
*chain.doFilter(request, response);
*/
}
public void init(FilterConfig config) throws
ServletException {this.config = config;
}
public void destroy() {
config = null;
}
/*
* FILTER METHOD
*/
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
/*
*
*chain.doFilter(request, response);
*/
}
}
in the above code, in doFilter method, write code to handle your session if the session is invalid just do response.sendRedirect to some default page, else do
chain.doFilter(request,response);
To make this filter work, add the following to your web.xml
<filter-name>AuthenticationFilter</filter-name>
<display-name>AuthenticationFilter</display-name>
<filter-class>com.AuthenticationFilter</filter-class>
</filter><filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
to make resources free from the filter define their urls seperately and find if the request is coming from that particular URLs else filter or proceed based on the need.