Cratylus
Cratylus

Reputation: 54074

java: question on filter and servlet mapping

I have a web application with the following structure:

TOMCAT_HOME
  |
   webapps
     |_myapp
          |-html/
          |-various directories
          |-WEB-INF/
          |-index.html

The application has various servlets that are registered over various paths.
The application itself can be accessed via http://IP:PORT/myapp/
This of courses causes to get the index.html (in the welcome list).
My question is, how would I register a filter for specifically the access of the root directory but not the subdirectories i.e. the url-mapping not to be /* If I place as url-pattern / seems not to work.
So the filter would intercept only this request http://IP:PORT/myapp/ and not http://IP:PORT/myapp/path or http://IP:PORT/myapp/servlet/path.
Additionally the filter would intercept a request like http://IP:PORT/myapp/index.html which is equivalent to the one I aim.

Thanks

Upvotes: 1

Views: 990

Answers (2)

Jeremy
Jeremy

Reputation: 22415

You can easily test for / and do your thing, otherwise let it pass through. With a /* URL pattern.

@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)
    throws IOException,ServletException{

    HttpServletRequest request=(HttpServletRequest)req;
    String path=request.getServletPath();

    if(path.equals("/") || path.equals("/index.html"){
        // do your thing
    }

    chain.doFilter(req,res);
}

Upvotes: 1

limc
limc

Reputation: 40168

Why not set the filter as /index.html then? It will not cause your subdirectories to be filtered.

Upvotes: 2

Related Questions