Java Web 项目学习(二) 检查登录状态

 为何要检查状态?

用户未登录情况下,也可以访问setting界面。修改头像信息。这显然是不合理的。

应该在服务端有个判断,登录可以访问,未登录拒绝。多请求相同逻辑,使用拦截器Interceptor。

拦截器需要做配置,配置类实现WebMvcConfig接口。 现在通过另一种方式实现————注解的方式。

元注解:

  • @Target  声明自定义注解可以作为(类/方法)上

  • @Retention   声明自定义注解作用时间(编译有效?运行有效?)  

  • @Document 声明自定义注解在在生成文档的时是否应该被加入

  • @Inherited 指定继承时子类是否继承父类的注解

反射调用:

  • Method.getDeclaredAnnotations()       获取这个方法至上的所有注解

  • Method.getAnnotation(Class<T> annotationClass)   获取指定类型的注解

示例:

  • 自定义注解:(新建annotation包,并在其下建立LoginRequire注解,建立时选择注解而非类。用来判断是否登录)
    /**
     * 注解作用判断是否已经登录
     */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface LoginRequired {
    
    }

    作用于方法,在运行时起作用。

  • 将注解应用到对应的方法中去。
    我们判断当前有两个界面需要判断用户是否登录。一个是Setting界面, 另一个是 处理上传文件的请求。将其注解上去。
      @LoginRequired
        @RequestMapping(path = "/setting", method = RequestMethod.GET)
        public String getSettingPage(){
            return "/site/setting";
        }
    
        /**
         * 处理上传文件的请求
         */
        @LoginRequired
        @RequestMapping(path = "/upload", method = RequestMethod.POST)
        public String uploadHeader (MultipartFile headerImg, Model model){....}
  • 写拦截器Loginrequire,实现HandlerInterceptor接口。
    根据需求,在Controller前拦截,因此使用preHandel方法。
    Object是我们拦截的目标,需要判断他是不是方法。  handler instanceof HandlerMethod 
    通过方法的反射获取指定类型的注解。 method.getAnnotation(LoginRequired.class) 
    如果未登录访问量需要登录才能访问的界面,就对他进行重定向。 response.sendRedirect(); 

    @Component
    public class LoginRequiredIntercepter implements HandlerInterceptor {
        @Autowired
        HostHolder hostHolder;
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //object 是我们拦截的目标
            if (handler instanceof HandlerMethod){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
                LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
                if(loginRequired != null && hostHolder.getUser()==null){
                    response.sendRedirect(request.getContextPath()+"/login");
                    return false;
                }
            }
            return true;
        }
    }
  • 配置拦截器。(这里主要是完成对静态资源访问的不拦截
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        @Autowired
        private AlphaInterceptor alphaInterceptor;
        @Autowired
        private LoginTicketIntercepter loginTicketIntercepter;
        @Autowired
        private LoginRequiredIntercepter loginRequiredIntercepter;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(alphaInterceptor) //拦截一切请求
                    .excludePathPatterns("/*/*.css","/*/*.js","/*/*.png","/*/*.jpg","/*/*.jpeg") //排除访问静态资源,所有目录下的cs文件
                    .addPathPatterns("/register","/login"); //拦截指定路径及其下的页面
    
    
            registry.addInterceptor(loginTicketIntercepter)
                    .excludePathPatterns("/*/*.css","/*/*.js","/*/*.png","/*/*.jpg","/*/*.jpeg");
    
            registry.addInterceptor(loginRequiredIntercepter)
                    .excludePathPatterns("/*/*.css","/*/*.js","/*/*.png","/*/*.jpg","/*/*.jpeg");
        }
    }




    完成这些之后,未登录状态下直接访问setting时,就会自动跳转到login界面。安全!

遇错:

 @Inherited用于描述该注解是否可以被其他注解继承。 (错误)

如果一个类用上了@Inherited修饰的注解,那么其子类也会继承这个注解。

但是:

接口用上个@Inherited修饰的注解,其实现类不会继承这个注解

父类的方法用了@Inherited修饰的注解,子类也不会继承这个注解

 

 

原文地址:https://www.cnblogs.com/codinghard/p/14843010.html