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.
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();
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