先定义一个拦截器注解
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface LoginRequired { }
在定义一个拦截器
/** * 登录拦截器 */ public class LoginInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { LoginRequired loginRequired = findAnnotation((HandlerMethod) handler, LoginRequired.class); //没有声明需要权限,或者声明不验证权限 if(loginRequired==null){ return true; }else{ String token=request.getHeader("token"); if(StringUtils.isEmpty(token)){ token=request.getParameter("token"); } //在这里实现自己的权限验证逻辑 if(!StringUtils.isEmpty(token)){//如果验证成功返回true(这里直接写false来模拟验证失败的处理) return true; }else{//如果验证失败 response.getWriter().write("您还未登录"); return false; } } }else{ return true; } } private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) { T annotation = handler.getBeanType().getAnnotation(annotationType); if (annotation != null) return annotation; return handler.getMethodAnnotation(annotationType); } }
spring配置
<!-- spring 3.1版本后才支持拦截方法名,需要引入一下配置 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<mvc:annotation-driven />
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.xxx.xxxx.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
Controller层数直接使用
@ResponseBody @RequestMapping(value="",method=RequestMethod.GET) @LoginRequired protected Map<String,Object> index(){ return null; }