登陆检查注解实现

在方法上添加一个注解,使用户在未登录时没有权限调用此方法。采用拦截器形式实现:

1、建一个注解类LoginCheck,代码入下:

@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginCheck {
    String value() default "";
}
2、建一个拦截器类:LoginCheckInterceptor

@Component
public class LoginCheckInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //不是方法直接跳过
        if(!(o instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handler = (HandlerMethod) o;
        Method method = handler.getMethod();
        //方法上是否有LoginCheck注解
        LoginCheck loginCheck = method.getAnnotation(LoginCheck.class);
        if(loginCheck != null){
            User user=(User) request.getSession().getAttribute("user");
            if(user != null){
                return true;
            }
        }else{
            return true;
        }
       response.sendRedirect("/toLogin.do");
       return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
3、启用拦截器,springboot中需要新建一个配置类并继承WebMvcConfigurerAdapter,重写addInterptors方法:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new LoginCheckInterceptor()).addPathPatterns("/**");
    }
}
大功告成,接下来只需要在需要登陆的接口上添加@LoginCheck注解测试即可。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值