您的位置 首页 java

Java 自定义注解实现后台获取当前登陆的用户信息

为什么需要在后台使用注解保存用户信息?

用户在前端页面进行一系列的操作,在请求后端接口时可能需要携带当前用户信息参数,这样的话前端也许要保存用户信息,不安全。在后端使用注解保存当前用户信息,安全方便。

1、核心代码

1.1、注解类

 import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginStaff {
    String key() default "loginStaff";
}
  

1.2、方法参数解析器类

 import java.util.Objects;
import com.baige.annotation.LoginStaff;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

public class LoginStaffResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginStaff.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request, WebDataBinderFactory factory) {
        LoginStaff staff = parameter.getParameterAnnotation(LoginStaff.class);
        return request.getAttribute(Objects.requireNonNull(staff).key(), NativeWebRequest.SCOPE_SESSION);
    }
}  

1.3、配置类

 import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

@Configuration
public class LoginStaffConfigurer implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new LoginStaffResolver());
    }

    @Bean
    public LoginStaffResolver LoginStaffResolver(){
        return new LoginStaffResolver();
    }
}  

2、注解的使用

在登录接口中往HttpSession中存放用户信息。

 session.setAttribute("loginStaff", staff);  

在需要使用注解的Controller接口方法参数添加@LoginStaff注解即可。

 @PostMapping("/add")
public RequestResult add(@LoginStaff Staff staff) {}  

如果您有什么好的想法与方法,欢迎评论区留言,我们一起讨论~

文章来源:智云一二三科技

文章标题:Java 自定义注解实现后台获取当前登陆的用户信息

文章地址:https://www.zhihuclub.com/180391.shtml

关于作者: 智云科技

热门文章

网站地图