r.r*_*uez 5 java spring spring-mvc interceptor
我试图在我的应用程序中配置拦截器,但我无法使其工作.
在我的应用程序配置类中,我已按以下方式配置:
@Configuration
@EnableWebMvc
public class AppContextConfiguration extends WebMvcConfigurerAdapter {
...
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());
}
...
}
Run Code Online (Sandbox Code Playgroud)
和拦截器:
public class MyInterceptor extends HandlerInterceptorAdapter{
private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
logger.debug("MyInterceptor - PREHANDLE");
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么没有被调用?
The*_*heo 20
我正在使用Spring Boot,并且addInterceptors()在调用拦截器时遇到了同样的问题,但拦截器在请求期间从未触发过.然而,XML配置没有问题.
基本上,你不需要这WebMvcConfigurerAdapter门课.你只需要声明一个@Bean类型MappedInterceptor:
@Bean
public MappedInterceptor myInterceptor()
{
return new MappedInterceptor(null, new MyInterceptor());
}
Run Code Online (Sandbox Code Playgroud)
拦截器类必须在spring context xml配置文件中的 tag 内声明<mvc:interceptors>。是你做的吗?
来自文档
注册应用于所有 URL 路径的拦截器的示例:
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)
注册仅限于特定 URL 路径的拦截器的示例:
<mvc:interceptors>
<mvc:interceptor>
<mapping path="/secure/*"/>
<bean class="org.example.SecurityInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)
因此,您需要在spring context xml文件MyInterceptor中配置类
| 归档时间: |
|
| 查看次数: |
7726 次 |
| 最近记录: |