b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

web项目jsp放在哪里 Spring Boot 静态资源处理(2)

电脑杂谈  发布时间:2018-01-23 17:02:32  来源:网络整理

如果我们想访问pic2.jpg,请求地址https://www.2cto.com/uploadfile/2018/0123/20180123100933670.jpg

上面我们介绍了Spring Boot 的默认资源映射,一般够用了,那我们如何自定义目录?

这些资源都是打包在jar包中的,然后实际应用中,我们还有很多资源是在管理系统中动态维护的,并不可能在程序包中,对于这种随意指定目录的资源,如何访问?

以增加 /myres/* 映射到 classpath:/myres/*为例的代码处理为:

实现类继承 WebMvcConfigurerAdapter 并重写方法 addResourceHandlers (对于 WebMvcConfigurerAdapter 上篇介绍的文章中已经有提到)

package org.springboot.sample.config;

import org.springboot.sample.interceptor.MyInterceptor1;
import org.springboot.sample.interceptor.MyInterceptor2;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebAppConfigurer 
        extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");
        super.addResourceHandlers(registry);
    }

}

访问myres 文件夹中的fengjing.jpg 图片的地址为https://www.2cto.com/uploadfile/2018/0123/20180123100933760.jpg

这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。

如果我们将/myres/* 修改为 /*与默认的相同时,则会覆盖系统的配置,可以多次使用 addResourceLocations 添加目录,优先级先添加的高于后添加的。

// 访问myres根目录下的fengjing.jpg 的URL为 https://www.2cto.com/uploadfile/2018/0123/20180123100932760.jpg (/** 会覆盖系统默认的配置)
// registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-62262-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...