SpringMVC: The precedence of @RequestMapping and Static Resource serving

霸气de小男生 提交于 2019-12-07 13:38:10

问题


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:

  1. Annotated controller methods
  2. Directly to view names
  3. Controller bean names
  4. Serve static resource requests
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!