19

I have a servlet which acts as a front controller.

@WebServlet("/*")

However, this also handles CSS and image files. How can I prevent this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Vadym
  • 407
  • 1
  • 6
  • 15

2 Answers2

24

You have 2 options:

  1. Use a more specific URL pattern such as /app/* or *.do and then let all your page requests match this URL pattern. See also Design Patterns web based applications

  2. The same as 1, but you want to hide the servlet mapping from the request URL; you should then put all static resources in a common folder such as /static or /resources and create a filter which checks if the request URL doesn't match it and then forward to the servlet. Here's an example which assumes that your controller servlet is a @WebServlet("/app/*") and that the filter is a @WebFilter("/*") and that all your static resources are in /resources folder.

    HttpServletRequest req = (HttpServletRequest) request;
    String path = req.getRequestURI().substring(req.getContextPath().length());
    
    if (path.startsWith("/resources/")) {
        chain.doFilter(request, response); // Goes to default servlet.
    } else {
        request.getRequestDispatcher("/app" + path).forward(request, response); // Goes to your controller.
    }
    

    See also How to access static resources when mapping a global front controller servlet on /*.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • @BalusC why do static resource throw 404 when loaded via controller. I had a filter mapped with /*. While loaded jquery file it throws and error 404 - resource not found. I resolved it by using the solution you have provided above. Can you please clear my doubts ? – Pooja Dubey Jul 17 '16 at 17:48
0

I know this is an old question and I guess @BalusC 's answer probably works fine. But I couldn't modify the URL for the JSF app am working on, so I simply just check for the path and return if it is to static resources:

    String path = request.getRequestURI().substring(request.getContextPath().length());
    if (path.contains("/resources/")) {
        return;
    }

This works fine for me.

Tunde Michael
  • 364
  • 4
  • 8