该拦截器用于判断用户在做操作之前是否登陆。
原博客地址: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。