检查登录状态

需要用元注解定义自己的注解

@Target:声明自定义的注解可以作用在哪个位置

@Retention:声明自定义注解保留的时间或者有效的时间(编译/运行)时有效

@Document:声明注解在生成文档的时候,是否带上注解

@Inherited:声明子类要不要继承

不写就默认不

1.新建包annotation

LoginRequired: 注解标识是否需要在登录的状态下才能访问

package com.nowcoder.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 {
}

2.新建拦截器判断是否为登录状态

在请求最初判断是否登录,重写preHandle方法

判断拦截的是否为方法

package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.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进行重定向
                response.sendRedirect(request.getContextPath()+"/login");
                return false;

            }


        }
        return true;
    }
}

3.在WebMvcConfig配置拦截器,过滤掉静态资源

@Autowired
    private LoginRequiredInterceptor loginRequiredInterceptor;
 public void addInterceptors(InterceptorRegistry registry) {
 registry.addInterceptor(loginRequiredInterceptor)
                .excludePathPatterns("/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg");
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值