2

I am using

<url-pattern>/*</url-pattern>

to map all the requests to one sevlet,where i do all the authentication work. but I want to skip some static content (like css files).so I tried fowrding them from that sevlet to where the resource file is

if(isResourceFile){
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("static/" + fileName);
    dispatcher.forward(request, response);
}

but this will start a infinite loop because this will again call the same sevlet

is there any way to work around this without mapping all the resource(css) files in web.xml?

Manu
  • 382
  • 5
  • 12

3 Answers3

2

The url-pattern of /* is better to be used exclusively by Filters, not Servlets. Put all your static files in a certain folder (maybe covered by the url-pattern of a more effective FileServlet?) and let the Filter check it.

E.g. (pseudo)

public void doFilter(request, response, chain) {
    if (requestURI.startsWith("/static")) {
        chain.doFilter(request, response); // Just continue. Do nothing.
    } else {
        request.getRequestDispatcher("/pages").forward(request, response); // Forward to page controller.
    }
}

See also:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Assuming that you're looking to authenticate just JSP files, you could change the URL:

/*.jsp

I think it's a better idea to handle your authentication using a filter rather than a servlet. And in a production environment, you should use a front-end webserver for static content.

kdgregory
  • 38,754
  • 10
  • 77
  • 102
0

In case you cannot use a filter and you have to use a wildcard '*' in the mapping without a extension like '.jsp' then then this could work for you:

if(isResourceFile){
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/static/" + fileName);
      dispatcher.forward(request, response);
      return; 
}

Adding the '/' in the beginning of the static directory will give it root context.

Punit Raizada
  • 494
  • 6
  • 11