Spring Boot入门十——拦截器

在Spring Boot项目中使用拦截器主要分为三步
step1:在控制器中创建不同的视图页面,其中有需要拦截的页面
step2:创建拦截器对象实现HandlerInterceptor接口,并实现接口的方法,在preHandler()方法中编写拦截规则,可以将拦截的对象重定向到其他页面

public class UserInterceptor implements HandlerInterceptor {
	//定义拦截规则
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User)request.getSession().getAttribute("user");
        if(null == user){
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/user/login/page");
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
}

step3:创建配置类,在该类中添加@Configuration注解,在addInterceptor方法中添加需要拦截的页面,和需要排除的页面

@Configuration
public class UserConfig implements WebMvcConfigurer {

    //定义拦截的路径和排除的路径
    String[] addPathPatterns = {"/user/**"};
    String[] excludePathPatterns = {
            "/user/login",
            "/user/login/page"};
    /**
     * 添加拦截的路径和排除的路径
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor())
                .addPathPatterns(addPathPatterns)
                .excludePathPatterns(excludePathPatterns);
    }
}

你可能感兴趣的:(servlet)