牛客网后端项目实战(十四):检查登录状态

  • 使用拦截器

    • 在方法前标注自定义注解
    • 拦截所有请求,只处理带有该注解的方法
  • 自定义注解

    • 常用的元注解:
      @Target、@Retention、@Document、@Inherited
    • 如何读取注解:
      Method.getDeclaredAnnotations ()
      Method.getAnnotation (Class annotationClass)

检查登录状态

登录和未登录的权限显然是不一致的,例如登录后可以进行账号的设置,而目前即便没有登录依旧可以通过直接输入网址的方式进入设置页面,显然这是不应该的。处理的方法是对特定的某某进行标注,再根据标注进行拦截/不拦截。

限制用户在未登录前访问到登录后的页面或者普通用户访问到管理员页面。

定义注解

根据注解进行拦截/不拦截

新建一个annotation包,包下新建一个annotation类。自定义注解需要用到常见的几个元注解,@Target是作用目标,可以是方法、类等。@Retention是生效时间,运行时有效、编译时有效等。这两个基本时必须写的,@Document文档是否记录,@Inherited是否继承。

package com.neu.langsam.community.annotation;


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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {

}

在需要拦截的方法前带上该注解

定义好注解后,在需要登录才能访问的方法上面加上注解,目前主要就是设置界面和上传头像需要登录。

定义拦截器

使用注解标记需要处理的方法后,定义拦截器进行统一处理。这里只对响应前/ controller前 进行处理,也就是只重写preHandle。

首先判断拦截对象是不是一个方法,如果是的话讲Object对象转型成HandlerMethod对象。获取拦截的方法,查找该方法有没有我们写的@LoginRequired注解。有的话看hostHolder里有没有user,如果有注解没user就重定向到登录页面,这里不是在controller层,所以需要用response 重定向。

package com.neu.langsam.community.controller.interceptor;

import com.neu.langsam.community.annotation.LoginRequired;
import com.neu.langsam.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        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;
    }
}

运行项目,在地址栏尝试直接访问设置页面,localhost:8080/community/user/setting,会发现跳转到了登录页面。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值