springboot 静态资源处理

使用springboot开发web应用,都会遇到处理静态资源(js,css,image等)的问题,基于springmvc开发,我们需要在需要在xml中定义,如:

<mvc:resources location="/static" mapping="/static/**"/>

在上述配置中,location定义了静态文件的实际存放路径,而mapping中定义的是浏览器访问静态资源的相对url,如过本地服务,访问对应图片路径为:http://localhost:8080/static/40836.jpg.

在springboot中,文件的存放路径都提供了相应的默认值与上边的location相对应:

  • Spring Boot 默认静态资源请求路径是/**,访问如:http://localhost:8080/40836.jpg.
  • SpringBoot默认资源存放路径是:classpath:/META-INF/resources,classpath:/resources,classpath:/static,classpath:/public/

    自定义静态资源配置

    Spring Boot提供两种静态资源配置方法

  • 通过application.properties
    Spring boot提供两个参数可以修改静态文件实际存放路径以及浏览器访问相对url,具体配置参看如下
spring.mvc.static-path-pattern=/static/** #修改静态访问路径为:http://localhost:8080/static/40836.jpg.
spring.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/statics/  #修改资源文件存放地址,如果多个用都好分割
  • 通过java代码配置实现动态资源修改
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")//配置访问路径
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");//配置文件存放路径,如果多个,通过链式编程逐个添加
     }
}

如果通过代码配置,首先要定义一个Config类,并且使用@Configuration注解标注,该类必须实现WebMvcConfigureAdapter,并且重写addResourceHandlers方法

猜你喜欢

转载自blog.csdn.net/wanghao_0206/article/details/80041602