SpringMVC:@RequestMapping 和静态资源服务的优先级 [英] SpringMVC: The precedence of @RequestMapping and Static Resource serving
问题描述
我有以下控制器处理程序方法的映射:
I have the following mapping for a controller handler method:
@RequestMapping(value = "login.html")
public String doLogin(Model model) {
return "login";
}
我对静态 *.html
资源有以下配置:
And I have the following configuration for static *.html
resource:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("*.html").addResourceLocations(("/static/"));
}
那么假设我正在访问 login.html
,哪个优先?任何关于 by-design
行为的官方文档?
So suppose I am visiting login.html
, which one will take the precedence?
Any official document about the by-design
behavior?
我想使用纯 HTML+JS
来查看我的应用程序.由于我不知道如何从控制器方法返回 HTML(有人说这是不可能的),我决定使用 static resource handler
来提供静态 HTML.但似乎我仍然需要为我的 Web 应用程序配置一个映射到根路径 /
的处理程序方法.虽然我已经在 /static/
路径下放置了一个 index.html
.即,我必须有这个:
I want to use pure HTML+JS
for the view of my application. Since I don't know how to return an HTML from a controller method (someone said it is not possible), I decided to serve the static HTML with static resource handler
. But it seems I still have to configure a handler method mapped to the root path /
for my web application. Although I have already placed an index.html
under the /static/
path. i.e., I must have this:
@RequestMapping(value = "/")
public String welcome(Model model) {
return "redirect:index.html"; //must prefix with "redirect:"
}
否则,当我点击 http://mysite/
时,我会收到 404
错误.
Otherwise, when I hit http://mysite/
, I will get a 404
error.
好像优先级是这样的:
请求来了->控制器请求映射->如果控制器中没有有效的映射,检查静态资源处理程序->如果没有找到有效的静态资源,404,哎呀...
request comes -> Controller request mapping -> If no valid mapping in controller, check static resource handler -> if no valid static resource found, 404, Oops...
添加 3 - 3 个可能的选项来提供静态资源.
我把问题移到这里:
ADD 3 - 3 possible options to serve static resource.
I moved the question to here:
推荐答案
WebMvcConfigurationSupport Javadoc 描述了默认注册的HandlerMapping
bean(即通过@EnableWebMvc
)以及它们的优先顺序.
The WebMvcConfigurationSupport Javadoc describes the HandlerMapping
beans registered by default (i.e. by @EnableWebMvc
) and their order of precedence.
映射URL路径时,顺序为:
When mapping URL paths, the order is:
- 带注释的控制器方法
- 直接查看姓名
- 控制器 bean 名称
- 处理静态资源请求
- 将请求转发到默认 servlet
即使您正在构建纯 HTML+JS"应用程序,您也可能希望将 index.html
转换为模板并利用一些 Spring MVC 功能,例如资源处理和缓存破坏您的静态资源.看看这个 Devoxx 演讲.
Even if you're building a "pure HTML+JS" application, you might want to turn that index.html
into a template anyway and leverage some Spring MVC features, such as resource handling and cache busting for your static resources. Take a look at this Devoxx talk.
这篇关于SpringMVC:@RequestMapping 和静态资源服务的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!