mas*_*ter 9 java spring-mvc spring-4
我有一个配置类,它扩展了WebMvcConfigurationSupport,我添加了这样的拦截器:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/api/**");
}
Run Code Online (Sandbox Code Playgroud)
在哪里myInterceptor():
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
Run Code Online (Sandbox Code Playgroud)
它适用于/api/**我已经实现的任何mapping()/api/sample- 来自MyInterceptor的preHandle被触发(我有一个带映射的Controller /api/sample).
当我调用不存在的资源时,例如/api/forward/sample从未调用MyInterceptor的preHandle.
请注意,当我在xml中使用配置时,它按预期工作,如:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/api/**" />
<bean class="my.pack.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)
出于某些原因,对于Java配置,不会拦截对不存在的映射的请求.为什么配置不相同?我认为应该是.
编辑:
多一点调试信息.使用xml配置DispatcherServlet#handlerMappings包含5个处理程序:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
org.springframework.web.socket.server.support.WebSocketHandlerMapping
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
org.springframework.security.oauth2.provider.endpoint.FrameworkEndpointHandlerMapping
org.springframework.web.servlet.handler.SimpleUrlHandlerMapping
Run Code Online (Sandbox Code Playgroud)
使用Java配置它包含7个处理程序:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
org.springframework.web.socket.server.support.WebSocketHandlerMapping
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
org.springframework.security.oauth2.provider.endpoint.FrameworkEndpointHandlerMapping
org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping
org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping
org.springframework.web.servlet.handler.SimpleUrlHandlerMapping
Run Code Online (Sandbox Code Playgroud)
问题似乎是SimpleUrlHandlerMapping(至少它似乎用于我调用的资源 - api/forward/sample而api/sample RequestMappingHandlerMapping在使用中)在基于Java的配置的情况下具有空的adopIterceptors.
编辑2:
示例应用程序的完整源代码(我试图尽量缩小以演示效果):https: //github.com/szprutamich/spring-demo
在类中ConfigurationBase- 配置可以从基于xml切换到基于静态字段的java CONFIG.
使用基于xml的配置,两个URL都有效:
/api/sample
/api/forward/sample
Run Code Online (Sandbox Code Playgroud)
使用基于java的config转发不起作用.
您的问题是关于“不存在的请求映射”,但在您的 XML 配置中,它存在:
<default-servlet-handler xmlns="http://www.springframework.org/schema/mvc" />
这为所有请求声明了一个默认处理程序,并且仅在找到有效处理程序时请求拦截器才起作用。删除这一行,您将在 XML 和 Java 配置中获得相同的行为:不会找到默认处理程序,并且拦截器将无法工作。
因此,为了让拦截器能够处理 Java 配置中的所有请求,您必须声明一个默认处理程序。您可以覆盖,configureDefaultServletHandling但据我所知,不可能在其上配置拦截器。您可能必须/**在默认处理控制器中显式映射。
| 归档时间: |
|
| 查看次数: |
1314 次 |
| 最近记录: |