smw*_*dia 5 java configuration spring spring-mvc
我是春天的新手。我注意到在处理静态资源时,有两个选项可用:
选项1:
如果使用以下代码DispatcherServlet将Spring映射到/,这使其成为“默认 Servlet”,则可以使用RequestMapping注释(覆盖AbstractAnnotationConfigDispatcherServletInitializer类)将某些静态资源映射到 Spring 处理程序:
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
Run Code Online (Sandbox Code Playgroud)
然后我们仍然可以启用容器的“默认 Servlet”来处理那些 URL 模式没有被 Spring 请求映射(覆盖WebMvcConfigurerAdapter类)覆盖的静态资源:
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
Run Code Online (Sandbox Code Playgroud)
这基本上使用servlet容器的“默认servlet”为包罗万象的处理所有的静态资源错过由Spring的DispatcherServlet。
选项 2:
(覆盖WebMvcConfigurerAdapter类)
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("*.efi").addResourceLocations("/");
}
Run Code Online (Sandbox Code Playgroud)
我通常选择选项 2,因为我想坚持使用 Spring,但我知道这不是一个强有力的理由。
一些与静态资源处理相关的参考:
添加 1
似乎选项 2 在资源映射方面提供了更大的灵活性。甚至WEB-INF可以映射文件夹内的资源。
下面是一个具体示例,说明何时回退到“默认”Servlet 来提供资源不适用。
这是上述方法的典型实现:
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
return;
}
Run Code Online (Sandbox Code Playgroud)
然而,当前在 Spring 4 中处理 404 错误的最佳实践似乎是使用setThrowExceptionIfNoHandlerFound:
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext)
{
DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,根据DispatcherServlet的文档:
请注意,如果
DefaultServletHttpRequestHandler使用 if ,则请求将始终转发到默认 servlet,并且NoHandlerFoundException在这种情况下永远不会抛出 a 。
确实如此。结合上述两种方法不会导致NoHandlerFoundException触发,这反过来又会阻止我的 404 自定义错误页面得到解决。现在,如果我要注释掉我的configureDefaultServletHandling方法,NoHandlerFoundException则会抛出 ,并且我的错误处理(通过@ControllerAdvice链接答案中所示)解析为我的自定义“notFoundPage”。
不幸的是,这现在意味着我的静态资源(即“default.css”)未解析:
DEBUG org.springframework.web.servlet.DispatcherServlet - Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'notFoundPage'; model is {}
org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /webapp-test/style/default.css
Run Code Online (Sandbox Code Playgroud)
我看不出有什么办法可以调和这两种方法,使它们不会相互干扰。我的结论是,“默认 Servlet”方法不适合在这种情况下提供静态资源,因此我们只能使用该addResourceHandlers方法。
addResourceHandlers使用该方法的好处包括:
另请参阅此答案,了解使用默认 servlet 处理静态资源如何导致不必要的副作用的更复杂示例。
| 归档时间: |
|
| 查看次数: |
2268 次 |
| 最近记录: |