Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring mvc filter for some controllers

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;
    }
}
like image 520
Tobia Avatar asked Feb 25 '16 08:02

Tobia


2 Answers

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.

like image 165
Ali Dehghani Avatar answered Sep 22 '22 20:09

Ali Dehghani


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 :)

like image 28
Magnus Avatar answered Sep 23 '22 20:09

Magnus