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

前端 未结 2 1186
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 17:13

I have a servlet which acts as a front controller.

@WebServlet(\"/*\")

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

相关标签:
2条回答
  • 2020-12-08 17:23

    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.

    0 讨论(0)
  • 2020-12-08 17:39

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

    0 讨论(0)
提交回复
热议问题