Home >Java >javaTutorial >How to Access Static Resources When Using a Global Front Controller Servlet in Spring MVC?
Accessing Static Resources with a Global Front Controller Servlet
When mapping a Spring MVC dispatcher as a global front controller servlet on /, it can lead to issues accessing static resources like CSS, JS, and images, which are typically stored in a folder like /res. This is because the / mapping captures all requests and routes them to the servlet, preventing access to these static files.
To address this, a more specific url-pattern can be defined for the controller servlet, such as /pages/. Static content can then be placed in a separate folder, such as /static. A Filter can be configured to listen on / and transparently pass requests for static content to the default servlet, while dispatching other requests to the controller servlet.
Here's a simplified code sample:
<filter> <filter-name>filter</filter-name> <filter-class>com.example.Filter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>controller</servlet-name> <servlet-class>com.example.Controller</servlet-class> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>/pages/*</url-pattern> </servlet-mapping>
And in the Filter's doFilter() method:
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 configuration ensures that static resources, such as CSS and JS, can be accessed without disrupting the functionality of the controller servlet, which handles the remaining requests. Additionally, the use of a Filter ensures that the static file access is fully transparent from a browser's perspective.
The above is the detailed content of How to Access Static Resources When Using a Global Front Controller Servlet in Spring MVC?. For more information, please follow other related articles on the PHP Chinese website!