Home > Java > javaTutorial > How Can I Access Static Resources with a Global Front Controller Servlet Mapped to /*?

How Can I Access Static Resources with a Global Front Controller Servlet Mapped to /*?

Barbara Streisand
Release: 2024-12-08 14:22:10
Original
357 people have browsed it

How Can I Access Static Resources with a Global Front Controller Servlet Mapped to /*?

Global Front Controller Servlet on /*: Resolving Static Resource Access

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:

1. Map the Controller Servlet on a Specific Path

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.

2. Implement a Filter for Static Content

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template