I need to process all request coming to some Spring controllers to get some requester informartion or to throw exceptions like a security filter.
I would like if is there something buildin in Spring like a filter for controllers (I need it not for all controller, but only for someone). I don't want to apply this filter by url request but with a class/method extension or annotation.
This is my actual solution:
@Controller
public class MyFilteredController extends FilterController {
@RequestMapping("/filtered")
public void test1(HttpServletRequest req){
InfoBean infobean=filter(req);
//... controller job
}
}
A controller that extends a class with a filter method.
public abstract FilterController{
protected InfoBean filter(HttpServletRequest req){
//... filter job
return infobean;
}
}
I don't want to apply this filter by url request but with a class/method extension or annotation
You can register a HandlerInterceptor
for this purpose. For example, you can apply a filter to all handler methods that annotated with SomeAnnotation
with following code:
public class CustomHandlerIntercepter extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
SomeAnnotation annotation = handlerMethod.getMethodAnnotation(SomeAnnotation.class);
if (annotation != null) {
// do stuff
}
}
return true;
}
}
Also, you should register your interceptor in WebConfig
:
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomHandlerIntercepter());
}
}
You can read more about interceptors in spring reference documentation.
Take a look at SpringSandwich http://springsandwich.com/
It lets you set filters (Spring Interceptors, actually) directly as controller annotations. Unlike normal servlet filters, you'll also have full access to your Spring context.
Disclosure: I'm the author of this framework :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With