Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent static resources from being handled by front controller servlet which is mapped on /*

Tags:

servlets

I have a servlet which acts as a front controller.

@WebServlet("/*")

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

like image 799
Vadym Avatar asked Nov 23 '12 00:11

Vadym


1 Answers

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 /*.

like image 141
BalusC Avatar answered Feb 07 '23 04:02

BalusC