问题
I have the following mapping for a controller handler method:
@RequestMapping(value = "login.html")
public String doLogin(Model model) {
return "login";
}
And I have the following configuration for static *.html
resource:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("*.html").addResourceLocations(("/static/"));
}
So suppose I am visiting login.html
, which one will take the precedence?
Any official document about the by-design
behavior?
ADD 1 Some background
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:"
}
Otherwise, when I hit http://mysite/
, I will get a 404
error.
ADD 2 -- some experiment result
It seems the precedence is like this:
request comes -> Controller request mapping -> If no valid mapping in controller, check static resource handler -> if no valid static resource found, 404, Oops...
ADD 3 - 3 possible options to serve static resource.
I moved the question to here:
Static resource serving in SpringMVC
回答1:
The WebMvcConfigurationSupport Javadoc describes the HandlerMapping
beans registered by default (i.e. by @EnableWebMvc
) and their order of precedence.
When mapping URL paths, the order is:
- Annotated controller methods
- Directly to view names
- Controller bean names
- Serve static resource requests
- Forward requests to the default servlet
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.
来源:https://stackoverflow.com/questions/34084784/springmvc-the-precedence-of-requestmapping-and-static-resource-serving