springboot 自定义注解 登录拦截验证
自定义注解
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface VerifyLogin {
boolean required() default true;
}
拦截器
import com.lideru.customannotation.web.configuration.VerifyLogin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//1.判断是否存在注解
if(!(handler instanceof HandlerMethod)){
System.out.println("不是HandlerMethod类型,不用检查");
return true;
}
HandlerMethod method = (HandlerMethod)handler;
boolean hasLoginAnnotation=method.getMethod().isAnnotationPresent(VerifyLogin.class);
if(!hasLoginAnnotation){
//不存在LoginRequired注解,则直接通过
System.out.println("不存在LoginRequired注解,则直接通过");
return true;
}
VerifyLogin loginRequired=method.getMethod().getAnnotation(VerifyLogin.class);
//2.required=false,则无需检查是否登录
if(!loginRequired.required()){
System.out.println("required=false,不用检查是否登录");
return true;
}
//3.登录状态检查,使用response返回指定信息
System.out.println("required=true,需检查是否登录");
response.getWriter().append("你需要就行登录才可以访问!");
return false;
}
}
配置类
import com.lideru.customannotation.web.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class LoginConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor());
}
}
测试控制器
import com.lideru.customannotation.web.configuration.VerifyLogin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
/**
* 不给LoginRequired注解,不需要验证是否登录
* @return
*/
@RequestMapping("index0")
public String index0(){
return "index0";
}
/**
* 给LoginRequired注解(默认是true),需要验证是否登录
* @return
*/
@VerifyLogin()
@RequestMapping("index1")
public String index1(){
return "index1";
}
/**
* 给LoginRequired注解(required = false),不需要验证是否登录
* @return
*/
@VerifyLogin( required = false)
@RequestMapping("index2")
public String index2(){
return "index2";
}
/**
* 给LoginRequired注解(required = true),需要验证是否登录
* @return
*/
@VerifyLogin(required = true)
@RequestMapping("index3")
public String index3(){
return "index3";
}
}
调用
http://127.0.0.1:8080/index0
http://127.0.0.1:8080/index1
http://127.0.0.1:8080/index2
http://127.0.0.1:8080/index3
结果如下:
不存在LoginRequired注解,则直接通过
required=true,需检查是否登录
required=false,不用检查是否登录
required=true,需检查是否登录
证明成功了!