I would like some help in understanding a particular behaviour of java Filters: I wrote a simple Filter which gets all user requests and, if a non-logged user requires a restricted resource, the filter forwards user to the home page. Here is my code:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
HttpServletRequest req = (HttpServletRequest) request;
String uri = req.getRequestURI();
System.out.println("\n\nFILTERING...\n\n");
//Se la risorsa appartiene all'area ristretta e l'utente non è
//loggato lo sbatto fuori
if(uri.contains("restricted") && (req.getSession(false) == null || req.getSession(false).getAttribute("user") == null)) {
System.out.println("\n\nCannot access\n\n");
//((HttpServletResponse) response).sendRedirect("/Hotel/index.jsp");
req.getRequestDispatcher("/index.jsp").forward(request, response);
}
else {
// pass the request along the filter chain
System.out.println("\n\nNext step\n\n");
chain.doFilter(request, response);
}
}
And the mapping in the web.xml:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>mycontroller.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What it is strange to me is that, if I ask a restricted resource via URL, the doFilter method is called several times before moving to the home (the server logs ‘FILTERING… Cannot access’ 4,5 times).
I’m using Tomcat 7.
Can someone help me to understand? Thanks a lot
You’ve mapped the filter on
/*. It will thus intercept on every single HTTP request. Not only HTML/JSP pages, but also static resources like CSS, JS and image files. Apparently you’ve requested a HTML/JSP page which in turn references several CSS, JS and/or image files.Your check in the filter is also pretty poor. You should rather map the filter on
/restricted/*.Then remove that URI check from the filter’s code. If you put those static resources outside that map, e.g. in
/staticor/resources, etc, then the filter won’t be invoked for them.