如何防止静态资源被映射到/* 的前端控制器 servlet 处理 [英] How to prevent static resources from being handled by front controller servlet which is mapped on /*
问题描述
我有一个充当前端控制器的 servlet.
I have a servlet which acts as a front controller.
@WebServlet("/*")
然而,这也处理 CSS 和图像文件.我怎样才能防止这种情况?
However, this also handles CSS and image files. How can I prevent this?
推荐答案
您有 2 个选择:
使用更具体的 URL 模式,例如
/app/*
或*.do
,然后让所有页面请求匹配此 URL 模式.另请参阅设计模式基于网络的应用程序
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
同1,但是你想对请求URL隐藏servlet映射;然后,您应该将所有静态资源放在一个公共文件夹中,例如 /static
或 /resources
并创建一个过滤器来检查请求 URL 是否与其不匹配,然后转发到 servlet.这是一个示例,假设您的控制器 servlet 是 @WebServlet("/app/*")
并且过滤器是 @WebFilter("/*")
和所有静态资源都在 /resources
文件夹中.
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.
}
另见如何访问静态资源在/*.
这篇关于如何防止静态资源被映射到/* 的前端控制器 servlet 处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!