您的位置:首页 > 编程语言 > Java开发

springMvc拦截器(HandlerInterceptorAdapter)

2017-03-02 10:44 369 查看
1、springMvc拦截器是对请求做共通处理,如权限验证,读取cookie,日志记录,乱码处理等,
2、拦截器只能拦截action请求;
3、拦截器可以调用IOC容器里的所有bean,这样一来可以直接调用业务方法。
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired annotation = method.getAnnotation(LoginRequired.class);
boolean needLogin = true;
boolean needAuth = true;
if (annotation != null) {
needLogin = annotation.needLogin();
needAuth = annotation.needAuth();
}
if (needLogin) {
//TODO
}
}
return true;
}
}LoginRequired是自定义的一个注解类,参考自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
boolean needLogin() default true;

boolean needAuth() default true;
}
1、通过实现接口HandlerInterceptor或继承类HandlerInterceptorAdapter将普通的bean改造为拦截器;2、重写preHandle()和postHandle(),为业务方法执行前后添加逻辑处理;3、通过继承WebMvcConfigurerAdapter或如下配置,注册拦截器
<!-- Spring MVC 拦截器注册 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/><!--只拦截匹配的请求路径-->
<bean class="com.changhf.plugin.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
只有preHandle() 返回true时,才会执行下一个拦截器,直到所有拦截器执行完后,才去运行被拦截的Controller。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: