Spring Boot中使用拦截器解决静态资源被拦截

时间:2022-12-31 20:52:29 类型:JAVA
字号:    

一,配置拦截器

public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
        logger.info("====拦截到了方法:{},在该方法执行之前执行====" );
    // 返回true才会继续执行,返回false则取消当前请求
        return true;
    }
}

二,解决静态资源被拦截

 方法一:

@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置拦截器
        registry.addInterceptor(new MyInterceptor())
                //对所有的资源进行拦截,包括静态资源
                .addPathPatterns("/**")
                .excludePathPatterns("/js/**", "/images/**","/css/**");
    }
}

方法二:

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }


    @Value("${ue.local.physical-path}")
    private String ueDir;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        //类路径 下的 static目录可以直接访问 
        registry.addResourceHandler("/uploads/**").addResourceLocations("file:"+ueDir);
        //file: + 绝对路径
        super.addResourceHandlers(registry);
    }


}

三. appliaction.yml文件

ue:
  config-file: static/ueditor/jsp/config.json #resources目录下配置文件的位置
  server-url: /ueditor.do #服务器统一请求接口路径
  local: #上传到本地配置
    url-prefix: /uploads/ #"/"结尾 自定义上传时字段无意义
    physical-path: F:/java/uploads/ #存储文件的绝对路径 必须使用标准路径"/"作为分隔符  自定义上传时字段无意义


<