Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom annotation on a Spring MVC controller method from an interceptor

I have a custom annotation with which I've annotated a method in my Controller alongside a @ReqestMapping.

The goal is to use the values set in the custom annotation from a HandlerInterceptor to perform a task.

I have the interceptor (HandlerInterceptorAdaptor) mapped and it executes. If I set a breakpoint in my concrete Interceptor I can inspect the HttpServletRequest, HttpServletResponse, and handler Objects. However, I cannot see how to 1, obtain the method which the request is trying to access 2, obtain the Annotations on that method and 3, of course, obtain the values set by the annotation.

Can anyone point me to good documentation for this?

Please and Thank You.

like image 448
Speck Avatar asked Jun 23 '11 23:06

Speck


People also ask

Which annotation can be used with controller?

The @Controller annotation indicates that a particular class serves the role of a controller. Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation.

What are the different methods handled by an interceptor in Spring boot?

Spring Handler Interceptor The HandlerInterceptor contains three main methods: prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed. afterCompletion() – called after the complete request is finished and the view is generated.

How does interceptor work in Spring MVC?

Spring Interceptor are used to intercept client requests and process them. Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods. That's where Spring MVC Interceptor come handy.


2 Answers

AOP will be a good fit for you. You should be able to write an advice which performs your task, with a joinpoint definition capturing the context of the called controller - Any custom annotations that you have, along with the passed parameters.

like image 34
Biju Kunjummen Avatar answered Oct 01 '22 14:10

Biju Kunjummen


in Spring 3.1 we've introduced a HandlerMethod abstraction to represent that specific controller method that will handle the request. There is HandlerMapping and a HandlerAdapter specifically for that. You can read about this in more detail in my blogpost following the M2 release.

https://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements/

Spring 3.1 is not released GA yet. Of course, it is available as a milestone release and also as a nightly snapshot. Either way, it is something you should take into consideration and hence worth mentioning.

like image 177
Rossen Avatar answered Oct 01 '22 14:10

Rossen