SpringBoot静态资源配置步骤
在SpringBoot项目里,如果不打算引入模板引擎,想要直接访问静态资源,需要进行特定的配置操作。
首先,需要在项目的application.yml配置文件中进行如下设置。
spring: profiles: active: dev mvc: view: prefix: / suffix: .html
这里的关键点在于

上述配置会被解析并生成WebMvcProperties配置类。该类内部包含一个名为View的内部类。
@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
View类用于配置视图的前缀和后缀属性。
public static class View {
/**
* Spring MVC view prefix. 前缀
*/
private String prefix;
/**
* Spring MVC view suffix. 后缀
*/
private String suffix;
其次,需要在项目的resource目录下新建相应的文件夹。
在ResourceHttpRequestHandler类的getResource方法执行时,会调用getLocations()方法。
protected Resource getResource(HttpServletRequest request) throws IOException {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
if (path == null) {
throw new IllegalStateException("Required request attribute '" +
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set");
}
path = processPath(path);
if (!StringUtils.hasText(path) || isInvalidPath(path)) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring invalid resource path [" + path + "]");
}
return null;
}
if (isInvalidEncodedPath(path)) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring invalid resource path with escape sequences [" + path + "]");
}
return null;
}
ResourceResolverChain resolveChain = new DefaultResourceResolverChain(getResourceResolvers());
//重点关注此处
Resource resource = resolveChain.resolveResource(request, path, getLocations());
if (resource == null || getResourceTransformers().isEmpty()) {
return resource;
}
ResourceTransformerChain transformChain =
new DefaultResourceTransformerChain(resolveChain, getResourceTransformers());
resource = transformChain.transform(request, resource);
return resource;
}
getLocations()方法返回的locations数组来源于SpringBoot项目的ResourceProperties配置类赋值。具体赋值的数据包括
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
这四个路径。
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
因此,为了能够成功访问静态资源,需要将资源文件放置在上述四个路径之一下,如图所示。

最后,API端代码编写示例如下。
@Controller
public class PageApi {
@GetMapping({"/", "/index"})
public String toPage(String id){
return "index";
}
}
总结:
完成以上配置后,即可正常访问到静态资源。

到此这篇关于SpringBoot在项目中访问静态资源步骤分析的文章就介绍到这了,更多相关SpringBoot访问静态资源内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!