Springboot2拦截器设置(不拦截静态资源)

  • 1 springboot2配置拦截器和Springboot配置有所不同,话不多说,showcode。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new SessionHandlerInterceptor());
        interceptorRegistration.excludePathPatterns("/error");
        interceptorRegistration.excludePathPatterns("/static/**");
        interceptorRegistration.excludePathPatterns("/login");

        interceptorRegistration.addPathPatterns("/**");


    }


    private class SessionHandlerInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

            Object user = request.getSession().getAttribute("user");
            if (user == null) {
                try {
                    response.sendRedirect("/login");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;

            }
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
            //controller方法处理完毕后,调用此方法
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            //页面渲染完毕后调用此方法
        }
    }
}
  • 2 重点在于
 interceptorRegistration.excludePathPatterns("/static/**");

这句会忽略静态资源。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,167评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,200评论 19 139
  • 第十四章 父母怎样才能不被“炒鱿鱼” 孩子不会反抗成年人---他们反抗的是成年人夺走他们自由的企图。 1、孩子越来...
    海上明月明阅读 270评论 0 0
  • 连续读完了两本小说《了不起的盖茨比》和《月亮与六便士》。抛开小说的其他不讲,我特别有兴趣对比一下两本小说里隐含着的...
    宋小song阅读 514评论 3 3
  • 离开一段时间后我又回归到这个大家庭,感赏老师们再次的接纳,给予我鼓励和帮助,感赏群内的朋友热情友爱,感赏自己能重新...
    张茹_阅读 196评论 0 1