springMvc基于注解登录拦截器

1.首先先定义一个拦截器注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
    
}

2.在定义一个拦截器

/**
 * 登录拦截器
 */
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);
    }
}

3.拦截器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>

4.Controller层数直接使用方法

@ResponseBody
@RequestMapping(value="",method=RequestMethod.GET)
@LoginRequired
protected Map<String,Object> index(){
    return null;
}

 

 

文章来源于:https://www.cnblogs.com/binz/p/6564606.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值