Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to Controller's method parameter values from Spring MVC interceptor

I'm developing a REST webservice with Spring MVC and I've implemented a custom annotation in order to annotate controller methods with it. This annotation may include a SpEL expression which I must evaluate considering controller method argument values. So, my idea is to implement a Spring MVC interceptor for this but the parameter HandlerMethod in the preHandle method is just a way to identify the method and does not provide access to controller method argument values. So, the only approach I can think of is to develop a Spring AOP aspect and intercept all the calls to annotated methods. By the way, I need access to the request, so if I go by the AOP way, all the annotated methods should include an argument with the request.

So, my question is: Is there any way to access the method argument values from thr Spring MVC interceptor or should I go the Spring AOP way?.

Thanks in advance.

like image 294
Juan Carlos González Avatar asked Jul 07 '14 06:07

Juan Carlos González


1 Answers

You cannot use the controller method parameter in the preHandle method of an interceptor, because at the time of calling it, the parameters of the controller method have not been constructed (except for request and response).

So you will have to go the AOP way (do not forget to implement a method in your controllers ...) like explained in JavaBond answer. But thanks to spring framework, you can avoid that all the annotated methods should include an argument with the request. RequestContextHolder.getRequestAttributes() gives you a RequestAttributes object. If you know that your request is a HttpServletRequest, you can cast it to a ServletRequestAttributes and then access the native request via the getRequest() method :

RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes();
HttpServletRequest req = ((ServletRequestAttributes) reqAttr).getRequest();
like image 196
Serge Ballesta Avatar answered Sep 25 '22 03:09

Serge Ballesta