专业的JAVA编程教程与资源

网站首页 > java教程 正文

自定义注解你真会用吗?(说说自定义注解的场景及实现)

temp10 2024-09-27 23:03:07 java教程 11 ℃ 0 评论

可以通过自定义注解来判断调用接口是否登录。下面是一种实现方式:

  1. 定义一个注解类@LoginRequired,用来标记需要登录才能调用的接口:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
  1. 在需要登录才能调用的接口上添加@LoginRequired注解:
@RestController
public class MyController {
    @GetMapping("/api/hello")
    @LoginRequired
    public String hello() {
        return "Hello World";
    }
}
  1. 编写一个拦截器,在调用接口前判断用户是否已登录。如果已登录,则放行;如果未登录,则返回错误信息:
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            LoginRequired loginRequired = handlerMethod.getMethodAnnotation(LoginRequired.class);
            if (loginRequired != null) {
                // 判断用户是否已登录
                HttpSession session = request.getSession();
                Object userId = session.getAttribute("userId");
                if (userId == null) {
                    // 用户未登录,返回错误信息
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("请先登录");
                    return false;
                }
            }
        }
        return true;
    }
}
  1. WebMvcConfigurer中添加拦截器:
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    }
}

这样,当调用添加了@LoginRequired注解的接口时,会先进入拦截器中进行判断,如果用户已登录,则放行;如果用户未登录,则返回错误信息。

自定义注解你真会用吗?(说说自定义注解的场景及实现)

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表