springMvc拦截器的使用

该拦截器用于判断用户在做操作之前是否登陆。

原博客地址:http://blog.csdn.net/chang_li/article/details/59482890


1、springMvc拦截器是对请求做共通处理,如权限验证,读取cookie,日志记录,乱码处理等,


2、拦截器只能拦截action请求;

3、拦截器可以调用IOC容器里的所有bean,这样一来可以直接调用业务方法。

[java] view plain copy
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是自定义的一个注解类,参考自定义注解
[java] view plain copy
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
boolean needLogin() default true;

boolean needAuth() default true;
}
通过spring提供的适配器org.springframework.web.servlet.handler.HandlerInterceptorAdapter,我们可以随意的定义我们自己的拦截器。spring-mvc.xml配置:
[html] view plain copy
<!-- Spring MVC 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/><!--只拦截匹配的请求路径-->
<bean class="com.changhf.plugin.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
只有preHandle() 返回true时,执行下一个拦截器,直到所有拦截器执行完,再运行被拦截的Controller。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值