java 注解 权限_java 使用注解 处理权限(springboot)
1、前端登陸,將用戶信息傳到后臺
2、后臺驗證賬號密碼,如果賬號密碼信息正確,將登陸的用戶信息保存到session中
3、自定義注解? 注解名為 CheckLogin
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CheckLogin {
}
4、寫一個攔截器,判斷你的方法或者類上是否存在@CheakLogin注解,如何存在 驗證賬號密碼是否正確
public class PermissionInterceptor extends HandlerInterceptorAdapter {
private SessionManager sessionManager;
@Autowired
public PermissionInterceptor(SessionManager sessionManager){
this.sessionManager = sessionManager;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod){
HandlerMethod hm = (HandlerMethod)handler;
handleClassCheckLogin(hm);
handleMethodCheckLogin(hm);
}
return super.preHandle(request, response, handler);
}
// 這里我判斷了類 或者 方法上面是否有我自定義的注解,如果有注解,就去從session中驗證用戶是否登陸成功
private void handleClassCheckLogin(HandlerMethod hm){
if ( AnnotationUtils.findAnnotation(hm.getBeanType(), CheckLogin.class) != null){
sessionManager.checkLogin();
}
}
private void handleMethodCheckLogin(HandlerMethod hm){
if ( hm.getMethodAnnotation(CheckLogin.class) != null){
sessionManager.checkLogin();
}
}
}
5、Springboot配置攔截器(spring mvc 直接在配置中配置就可)
/**
* web攔截器,檢查是否登陸
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public SessionManager getSessionManager(){
return new SessionManager();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PermissionInterceptor(getSessionManager())).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
6、ok了,在你和前端交互的那一層 類上或方法上打上cheacLogin吧
總結
以上是生活随笔為你收集整理的java 注解 权限_java 使用注解 处理权限(springboot)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java equals 区别_Java中
- 下一篇: java 字符串驻留_java Stri