Spring中 interceptor 获取方法级对象

时间:2025-04-04 10:49:58


背景:在拦截器中,对Controller中的方法级注解判断,控制用户访问权限

实现:

中配置拦截器

<mvc:interceptors><mvc:interceptor><mvc:mapping path="/**"/><bean  class=".OAuth2Interceptor" /></mvc:interceptor></mvc:interceptors>


 

自定义注解OAuthRequired

import .*;

@Retention()
@Target()
public @interface OAuthRequired {
	
}

Controller类

@Controller
@RequestMapping("/aircraftInfo")
public class AircraftInfoController {
@RequestMapping("/")
<span>	</span>@OAuthRequired
<span>	</span>public  String getAircraftInfoModel(){ ....}


定拦截器:OAuth2Interceptor , 继承HandlerInterceptor ,实现三个方法afterCompletion ,postHandle ,preHandle,在Controller处理之前执行preHandle
public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		("**执行顺序: 1、preHandle**");
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = ();
if (()) {....}
}
在程序执行到
HandlerMethod handlerMethod = (HandlerMethod) handler;

时将报以下异常:

cannot be cast to   

 

修改拦截器的的注入方式:

<bean class="" >
	
	 <property name="interceptors">  
        <list>  
            <bean class=".OAuth2Interceptor">
	            <property name="excludedUrls">
	                <list>
	                    <value>/oauth2</value>
	                </list>
	            </property>
            </bean>  
        </list>  
    </property>  
	</bean>   

这样用户请求时, 后台才会拦截到方法级的handler