Reputation: 1583
I have an interceptor that is supposed to intercept urls with different patterns like:
I have to intercept all urls which contain "add". There are a lot of somethings and somethingelses...
I have tried different patterns but it seems that they are all wrong:
The interceptor is something like
public class MyInterceptor implements HandlerInterceptor {
}
I configure it in
@Configuration
@EnableSpringDataWebSupport
@EnableWebMvc
class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(getMyInterceptor()).addPathPatterns("**/add/*", "**/add/**", "**/add*");
}
@Bean
public MyInterceptor getMyInterceptor() {
return new MyInterceptor();
}
}
If I try to access
http://localhost:8080/myapp/something/add/somethingelse
my interceptor doesn't intercept it...
Upvotes: 2
Views: 4225
Reputation: 9179
I had a similar issue. Here are my suggestions.
First use global interceptor and check the request uri:
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
if(uri.contains("/add")){
// do your job
}
return super.preHandle(request, response, handler);
}
}
In my case, alls add
- methods are PUT
, or POST
requests. So I'm checking this in my global interceptor:
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String method = request.getMethod();
if("PUT".equals(method) || "POST".equals(method)){
// do your job
}
return super.preHandle(request, response, handler);
}
}
configure it without addPathPatterns
:
@Configuration
@EnableSpringDataWebSupport
@EnableWebMvc
class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(getMyInterceptor());
}
@Bean
public MyInterceptor getMyInterceptor() {
return new MyInterceptor();
}
}
Upvotes: 1
Reputation: 39224
Apparently this can be fixed by Change the bean type to "Mapped Interceptor" and wrapping it; though people don't seem to know why its an issue in the first place.
Based on this solution: https://stackoverflow.com/a/35948730/857994
Upvotes: 0