Title

springboot本地图片映射虚拟路径

配置图片直接访问

  • 编写一个配置类(名字任意取) 继承(extends)WebMvcConfigurationSupport 类
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

}
  • 在 application.properties 配置图片的本地位置
users.upload.path=D:\\images\\
  • 获取本地位置
    //本地图片路径
    @Value("${users.upload.path}")
    private String uploadConfig;
  • 在配置类 CORSConfiguration 里添加图片映射
//图片绝对地址与虚拟地址映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/images/**")) {
            registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadConfig);
            super.addResourceHandlers(registry);
        }
    }

然后就能进行请求url地址访问了

请求url地址访问不到被springMVC拦截的解决办法

  • 编写一个拦截器进行拦截
@Component
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        return true;
    }
}
  • 在 CORSConfiguration 配置类里添加springMVC拦截配置
    //配置springMVC部分拦截
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebInterceptor())                   //添加拦截器
                .addPathPatterns("/**")                    //拦截所有请求
                .excludePathPatterns("/images/**");    //对应的不拦截的请求

        super.addInterceptors(registry);
    }

addInterceptor里面的拦截器就是编写的拦截器

然后就可以请求图片资源的url地址了,例如:http://localhost:8080/images/a.jpg

解决配置类继承WebMvcConfigurationSupport后swagger无法正常访问

访问swagger页面404

查看swagger的配置

SwaggerUiWebMvcConfigurer 中配置了swagger静态资源访问路径,所以将其合并到自己的配置类中即可

 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }

    }

完整代码:

import lombok.SneakyThrows;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

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

/**
 * 解决跨域问题
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    private final static String FILE_DIR="/home/";

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/"};

    //    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /* 是否允许请求带有验证信息 */
        corsConfiguration.setAllowCredentials(true);
        /* 允许访问的客户端域名 */
        corsConfiguration.addAllowedOrigin("*");
        /* 允许服务端访问的客户端请求头 */
        corsConfiguration.addAllowedHeader("*");
        /* 允许访问的方法名,GET POST等 */
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

    @SneakyThrows
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/word/**")) {
            registry.addResourceHandler("/word/**").addResourceLocations("file:" + FILE_DIR);
        }
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebInterceptor())                   //添加拦截器
                .addPathPatterns("/**")                    //拦截所有请求
                .excludePathPatterns("/word/**");    //对应的不拦截的请求
        super.addInterceptors(registry);
    }
}

class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        return true;
    }
}

Java读取resources下的文件及资源路径

posted @ 2021-11-18 16:19  快乐小洋人  阅读(489)  评论(0编辑  收藏  举报