SpringBoot拦截器的简单实现

1、首先完成拦截后的处理逻辑,本次的规则比较简单只需判断请求头里是否包含Ticket字段,包含且有效则进行放行

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TicketInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("Ticket".equals(cookie.getName()) && cookie.getValue() != null) {
                return true;
            }
        }
        return false;
    }

}

2、编写拦截规则,需要拦截哪些请求

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 WebConfig  implements WebMvcConfigurer {
    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 对访问路径进行拦截
        registry.addInterceptor(new TicketInterceptor())
                .addPathPatterns("/**") //对所有路径进行拦截
                .excludePathPatterns("/user/**","/api/**");//放行路径
    }
}

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