springboot读取静态资源文件的方式

时间:2019-10-15
本文章向大家介绍springboot读取静态资源文件的方式,主要包括springboot读取静态资源文件的方式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

springboot的请求路径一般会经过Controller处理,但是静态资源文件在请求之后是直接返回的。这涉及到俩个配置项。

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
上面俩个是他们的默认配置,如果项目中没有任何配置,项目会以这种配置执行。

spring.mvc.static-path-pattern指的是请求路径。
spring.resources.static-locations指的是,静态资源目录,目录按配置顺序由先到后,优先级由高到低。
举例说明:
如果配置为
spring.mvc.static-path-pattern:/static/**,
spring.resources.static-locations:classpath:/static/,classpath:/public/

即http://localhost:8088/static/index.html的请求会是一个静态请求;而http://localhost:8088/index.html的请求不是一个静态请求。
那么http://localhost:8088/static/index.html这个请求,就会在现在static目录下,寻找index.html文件(注意:寻找的是index.html文件,而不是static/index.html),如果找到了响应请求,如果找不到,再在public文件夹下寻找。在需要注意的是,在

这种配置方式是在application.properties文件中配置的,除此之后还可以在项目中配置。
项目中配置方式:
package com.tsinkai.ettp.config;

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 WebMvcConfig extends WebMvcConfigurerAdapter{

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

这两种方式的配置是同事存在的,并不冲突。

另外写在html中的静态路径需要注意的问题:

正确写法:<script src="/static/layui/layui.js">

错误写法:<script src="static/layui/layui.js">

static前的/,一定要写好,否则会在请求js时出现404.

原因:

正确请求的路径:http://localhost:8088/static/layui/layui.js

错误请求的路径:http://localhost:8088/thymeleaf/static/layui/layui.js

即,如果不写/,那么最终的请求会加上处理该请求的Controller类的RequestMapping,如图

原文地址:https://www.cnblogs.com/whalesea/p/11678200.html