Home >Java >javaTutorial >How Can I Access Static Resources with a Global Front Controller Servlet Mapped to /*?
When mapping a global front controller servlet on /*, it becomes a challenge to access static resources like CSS, JS, and images that are typically stored in a separate folder. This article delves into a solution to restore access to these static files while maintaining the global front controller functionality.
The recommended approach involves two steps:
Instead of using / as the URL pattern for the controller servlet, map it on a more specific path, such as /pages/. This will allow static resources to be excluded from the controller's reach.
Create a filter that listens on /*. This filter will transparently continue the chain for any request to static resources and dispatch requests to the controller servlet for other content.
In the filter's doFilter() method, use the following code:
HttpServletRequest req = (HttpServletRequest) request; String path = req.getRequestURI().substring(req.getContextPath().length()); if (path.startsWith("/static")) { chain.doFilter(request, response); // Goes to default servlet. } else { request.getRequestDispatcher("/pages" + path).forward(request, response); }
This code checks if the request path starts with "/static" (or any other prefix assigned to static resources). If true, the request is forwarded to the default servlet which typically maps to the static resource folder. Otherwise, the request is dispatched to the controller servlet (assuming it is mapped on */pages).
This solution ensures that static resources are excluded from the controller servlet's mapping, while allowing other requests to be processed by the controller as expected. It's a practical way to balance the need for a global front controller with the accessibility of static resources.
The above is the detailed content of How Can I Access Static Resources with a Global Front Controller Servlet Mapped to /*?. For more information, please follow other related articles on the PHP Chinese website!