【Java Web】检查用户登录状态,防止用户访问到非法页面

  • 使用拦截器
    • 在方法前标注自定义注解
    • 拦截所有请求,只处理带有该注解的方法
  • 自定义注解:
    • 常用元注解:@Target, @Rentention, @Document, @Inherited
    • 如何读取注解:
      - Method.getDeclaredAnnotations()
      - Method.getAnnotaion(Class annotationClass)

业务场景:未登陆状态下,用户不能访问需要登陆才能访问的页面,例如修改个人信息页面等。

1. 自定义注解

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. 在方法前加上该注解

@LoginRequired
@RequestMapping(path = "/setting",method = RequestMethod.GET)
public String getSettingPage(){
    return "/site/setting";
}

3. 定义拦截器

package com.nowcoder.community.controller.Interceptor;


import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
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 LoginRequireInterception 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) {  // 方法是loginRequired且user没登陆,需要拦截
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }

        return true;
    }
}

4. 配置拦截器

package com.nowcoder.community.config;

import com.nowcoder.community.controller.Interceptor.AlphaInterceptor;
import com.nowcoder.community.controller.Interceptor.LoginRequireInterception;
import com.nowcoder.community.controller.Interceptor.LoginTicketInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private AlphaInterceptor alphaInterceptor;

    @Autowired
    private LoginTicketInterceptor loginTicketInterceptor;

    @Autowired
    private LoginRequireInterception loginRequireInterception;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 通过重写addInterceptors()方法,可以配置拦截器,对请求进行预处理或后处理。
        registry.addInterceptor(loginRequireInterception)
                .excludePathPatterns("/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg");

    }

}

你可能感兴趣的:(java,java,spring,spring,boot)