Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring mvc get mapping controller method from interceptor

Now I have a controller like this

@RequestMapping("/content/delete.json")
@Security(auth = AuthType.REQUIRED)
public ModelAndView deleteIndex(User user, @RequestParam("id") long id) {

}

Now I am trying to get controller mapping method from interceptor and getting the annotation of the method.

Method method = RestRequestURLUtil.getInvokedMethod(handler, request);
Security security = method.getAnnotation(Security.class);
if(security.getAuth() == AuthType.REQUIRED) {
    do some validate here
}

Are there any classes like RestRequestURLUtil in spring?

thanks in advance :)

edit:

web.xml

<servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/rest-servlet.xml,
                /WEB-INF/interceptor-servlet.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

interceptor-server.xml

<mvc:interceptors>
    <mvc:interceptor>
    <mvc:mapping path="/**" />
    <bean class="com.test.web.interceptors.SecurityInterceptor" init-method="init">
     ...
    </bean>
</mvc:interceptor>
like image 926
Felix Avatar asked Mar 19 '23 23:03

Felix


1 Answers

The annotation on the controller's method can be inspected in the interceptor by means of the HandlerMethod object that the framework should pass as handler Object.

if (handler instanceof HandlerMethod) {
    HandlerMethod method = (HandlerMethod) handler;
    if (method.getMethod().isAnnotationPresent(Security.class)) {
       //do processing
    }
}

However, according to the spring documentation in HandlerMethod javadoc, HandlerMethod class was introduced in Spring 3.1. It seems that, in versions prior to 3.1, handler object was a Controller instance, which makes fetching the annotation of the invoked controller method difficult.

You can either upgrade to 3.1. and fetch the annotation from HandlerMethod object or attempt to parse all the RequestMapping annotations on the controller methods and then attempt to determine which method was invoked by comparing RequestMappings with request URI.

If upgrade is not an option, another alternative would be to use AOP instead of mvc interceptor.

like image 168
Krešimir Nesek Avatar answered Apr 06 '23 01:04

Krešimir Nesek