zoukankan      html  css  js  c++  java
  • springMvc基于注解登录拦截器

    先定义一个拦截器注解

    @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;
    }
  • 相关阅读:
    基于前后端分离的身份认证方式——JWT
    java远程文件操作
    BZOJ3181: [Coci2012]BROJ
    回归本源--位运算及其应用
    BZOJ 1226: [SDOI2009]学校食堂Dining
    BZOJ2734: [HNOI2012]集合选数
    BZOJ2064: 分裂
    BZOJ2679: [Usaco2012 Open]Balanced Cow Subsets
    OI队内测试——石门一
    Codeforces Round #376 (Div. 2)
  • 原文地址:https://www.cnblogs.com/binz/p/6564606.html
Copyright © 2011-2022 走看看