登录拦截器

定义注解和拦截器

自定义注解,对标记了注解的方法进行拦截

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireLogin {
    /**
     * @return true 时不检查,false 时检查
     */
    boolean value() default true;
}

定义拦截器,根据注解进行方法拦截

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RequireLogin loginRequire = method.getAnnotation(RequireLogin.class);
        if (loginRequire == null) {
            return true;
        }
        if (loginRequire.value()) {
            return true;
        }
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            //登录成功,不拦截
            return true;
        } else {
            //未登录,拦截
            return false;
        }
    }
}

配置拦截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");
    }
}

使用

@RestController
public class HelloController {
    @RequestMapping("/login")
    public String login(HttpSession session) {
        session.setAttribute("user", "user");
        return "登录成功";
    }

    @RequestMapping("/hello1")
    @RequireLogin(false)
    public String hello1(HttpSession session) {
        return "Hello Spring";
    }

    @RequestMapping("/hello2")
    @RequireLogin(true)
    public String hello2(HttpSession session) {
        return "Hello Spring";
    }
}

你可能感兴趣的:(登录拦截器)