springboot配置拦截器不能放行静态资源

新建一个拦截器类,实现 org.springframework.web.servlet.HandlerInterceptor 接口,重写preHandle、postHandle、afterCompletion方法分别是处理前、处理中、处理后。

public class RequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("目标方法执行前!");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("目标方法执行时!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("目标方法执行后!");
    }}

在配置类中添加该拦截器,如下:

方式一:根据后缀放行,这样要是文件类型很多的话是不是就很麻烦呢

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(new RequestInterceptor());
        registration.addPathPatterns("/**");                      //所有路径都被拦截
        registration.excludePathPatterns(                         //添加不拦截路径
                                         "/**/*.html",
                                         "/**/*.js",              //js静态资源
                                         "/**/*.css",             //css静态资源
                                         "/**/*.woff",
                                         "/**/*.ttf"
                                         );
    }
}
方式二:有个问题就是:静态资源是默认static下的,请求路径中没有static,所以放行不成功
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

    registry.addInterceptor(new     RequestInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/login","/logout","/static/**");
}

方式三:就是直接配置拦截所有,然后在拦截器中对url筛选,只要是请求的静态资源就直接返回true,但是感觉做了一些无用功

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
      registration.addInterceptor(new RequestInterceptor()).addPathPatterns("/**");
  }}

//拦截器中

 @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean check = false;
        StringBuffer url = request.getRequestURL();
       if(isStatic(url)){
           check = true;
       }else{
           Object auth = request.getSession().getAttribute("auth");
           if(auth == null){
               String scheme = request.getScheme();
               String serverName = request.getServerName();
               int port = request.getServerPort();
               String context = request.getContextPath();
               String path = scheme+"://"+serverName+":"+port+context+"/";
               String str = "<script language=‘javascript‘>alert(‘登录状态过期,请重新登陆!‘);"
                       +"if (window != top){top.location.href = ‘"+ path +"login‘;}location.href=‘"+path+"login‘"
                       +"</script>";
               response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
               try {
                   PrintWriter writer = response.getWriter();
                   writer.write(str);
                   writer.flush();
                   writer.close();
               } catch (Exception e) {e.printStackTrace();}
           }else{
               check = true;
           }
       }
       return  check;
    }

    @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 {

    }
  
    public boolean isStatic(StringBuffer url) {
        boolean result = false;
        String[] arr = { //定义一个需要放行的数组
                "/login",
                "/css",
                "/images",//图片
                "/js" //js脚本
        };
        for (String a : arr) {
            if (url.indexOf(a) != -1) {
                result = true;
            }
        }
        return result;
    }

//excludePathPatterns放行是? 请求路径中包含你所配置的就ok,还是你请求的是这个目录下的资源就可以呢?

原文地址:https://www.cnblogs.com/shewuxuan/p/12660459.html

时间: 2024-11-09 01:45:34

springboot配置拦截器不能放行静态资源的相关文章

Spring Mvc Web 配置拦截规则与访问静态资源 (三)

拦截规则配置 1. *.do <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name

SpringBoot配置拦截器

[配置步骤] 1.为类添加注解@Configuration,配置拦截器 2.继承WebMvcConfigurerAdapter类 3.重写addInterceptors方法,添加需要拦截的请求 @Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { //表示拦

关于Spring boot2.0+配置拦截器拦截静态资源的问题

第一次遇到这个问题的时候,简直是一脸蒙逼,写了一个拦截器以后,静态资源就不能访问了,到处查找才知道是版本问题 解决办法: 第一步:定义一个类实现 实现WebMvcConfigurer的类中拦截器中添加放行资源处添加静态资源文件路径: @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sessionInterceptor).addPathPatterns("/&

27.Spring-Boot中拦截器中静态资源的处理(踩过坑)以及Spring mvc configuring拓展介绍

一.springboot中对静态资源的处理 默认情况下,springboot提供存放放置静态资源的文件夹: /static /public /resources /META-INF/resources 对于maven项目即就是存在src/main/resources 文件夹下. ? 如图:static文件夹就是springboot中默认的文件夹 在页面中这样写路径<link href="themes/bootstrap.min.css" rel="stylesheet&

springboot+springmvc拦截器做登录拦截

springboot+springmvc拦截器做登录拦截 LoginInterceptor 实现 HandlerInterceptor 接口,自定义拦截器处理方法 LoginConfiguration 实现 WebMvcConfigurer 接口,注册拦截器 ResourceBundle 加载 properties文件数据,配置不进行拦截的路径 LoginInterceptor package com.ytkj.smart_sand.system.interceptor; import com.

spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项

原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory" /> </bean>

struts 2配置拦截器

在struts.xml文件中定义拦截器只需要为拦截器类指定一个拦截器名就可以了,拦截器使用<interceptor.../>元素来定义如: <interceptor name="defaultStack"/> 一般情况下,只需要通过上面的格式就可以完成拦截器的配置,如果需要在配置拦截器时传入拦截器参数,可使用<param.../>子元素.如: <interceptor name="defaultStack"/> <

spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对比与注意事项

原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory" /> </bean>

spring-boot 加入拦截器Interceptor

1.spring boot拦截器默认有 HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationInterceptor LocaleChangeInterceptor ThemeChangeInterceptor 2.配置spring mvc的拦截器WebMvcConfigurerAdapter public class WebAppConfig extends WebMvcConfigurerAdapter 3