SpringBoot
项目使用 Maven
构建,导入 web
模块,pom.xml文件如下
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.5.RELEASE
com.jiker
springboot-web
0.0.1-SNAPSHOT
springboot-web
Demo project for Spring Boot
11
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
若是原来的web应用时,应用中的静态资源将放在webapp目录下
如今,项目打包方式为 jar
,若需要放入静态资源文件,则需要了解 SpringBoot 的静态资源映射规则
在 Spring Boot
应用中,SpringMVC
的相关配置都是在 WebMvcAutoConfiguration
中
查看该类源码一部分
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
该方法名为 addResourceHandlers
:添加资源映射
规则1、所有 /webjars/**
请求,都去 classpath:/META-INF/resources/webjars/
下寻找资源
webjars
:以 jar
包的方式引入资源,参考:https://www.webjars.org/
例子:若项目中需要引入 jQuery
,原 Web 应用的方式是将 jQuery.js
文件导入到 webapp文件夹中
现在可以通过 webjars
,以 jar
包的方式导入 jQuery
在官网中搜索需要的插件
将依赖导入进 pom.xml
文件中
org.springframework.boot
spring-boot-starter-web
org.webjars
jquery
3.3.1
org.springframework.boot
spring-boot-starter-test
test
查看依赖
发现该文件夹目录已经和映射规则 classpath:/META-INF/resources/webjars/
对应
即,现可以发送:http://localhost:8080/webjars/jquery/3.3.1/jquery.js 查看 jquery 源码
规则2、“/**”
访问当前项目的任何资源(静态资源文件夹)
在源码中的另一个规则 String staticPathPattern = this.mvcProperties.getStaticPathPattern();
获取静态资源路径
该方法的源码如下
public String getStaticPathPattern() {
return this.staticPathPattern;
}
public class WebMvcProperties {
private Format messageCodesResolverFormat;
private Locale locale;
private WebMvcProperties.LocaleResolver localeResolver;
private String dateFormat;
private boolean dispatchTraceRequest;
private boolean dispatchOptionsRequest;
private boolean ignoreDefaultModelOnRedirect;
private boolean throwExceptionIfNoHandlerFound;
private boolean logResolvedException;
private String staticPathPattern;
private final WebMvcProperties.Async async;
private final WebMvcProperties.Servlet servlet;
private final WebMvcProperties.View view;
private final WebMvcProperties.Contentnegotiation contentnegotiation;
private final WebMvcProperties.Pathmatch pathmatch;
public WebMvcProperties() {
this.localeResolver = WebMvcProperties.LocaleResolver.ACCEPT_HEADER;
this.dispatchTraceRequest = false;
this.dispatchOptionsRequest = true;
this.ignoreDefaultModelOnRedirect = true;
this.throwExceptionIfNoHandlerFound = false;
this.logResolvedException = false;
this.staticPathPattern = "/**";
this.async = new WebMvcProperties.Async();
this.servlet = new WebMvcProperties.Servlet();
this.view = new WebMvcProperties.View();
this.contentnegotiation = new WebMvcProperties.Contentnegotiation();
this.pathmatch = new WebMvcProperties.Pathmatch();
}
... ...
即默认路径为 this.staticPathPattern = "/**";
通过 getStaticLocations()
方法源码可知
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
若访问 http://localhost:8080/xxx 无任何处理时,则去以下文件夹下寻找资源
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/ : 当前项目的根路径
即可以将 css
、js
、img
等文件放在以下目录中
规则3、首页;静态资源文件夹下所有的 index.html
页面;被 “/**”
映射
同样在 WebMvcAutoConfiguration
中查看以下源码
//配置首页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
}
//WelcomePageHandlerMapping 方法
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext, Optional welcomePage, String staticPathPattern) {
if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage.get());
this.setRootViewName("forward:index.html");
} else if (this.welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
logger.info("Adding welcome page template: index");
this.setRootViewName("index");
}
}
在静态资源文件夹中创建一个 index 页面,之后通过 http://localhost:8080/ 进行访问
首页 index.html
得到映射
规则4、所有的 **/favicon.ico
都是在静态资源文件夹中映射(配置网页图标)
//配置网页图标
@Configuration
@ConditionalOnProperty(
value = {"spring.mvc.favicon.enabled"},
matchIfMissing = true
)
public static class FaviconConfiguration implements ResourceLoaderAware {
private final ResourceProperties resourceProperties;
private ResourceLoader resourceLoader;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resolveFaviconLocations());
return requestHandler;
}
private List resolveFaviconLocations() {
String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations());
List locations = new ArrayList(staticLocations.length + 1);
Stream var10000 = Arrays.stream(staticLocations);
ResourceLoader var10001 = this.resourceLoader;
var10001.getClass();
var10000.map(var10001::getResource).forEach(locations::add);
locations.add(new ClassPathResource("/"));
return Collections.unmodifiableList(locations);
}
}
从网上下载一个 .ico
文件当作图标:https://www.easyicon.net/
在静态资源文件夹中引入网页图标
Spring Boot 推荐使用 Thymeleaf
模板引擎
官网:https://www.thymeleaf.org/
1、引入thymeleaf模板引擎
org.springframework.boot
spring-boot-starter-thymeleaf
2、thymeleaf使用&语法
查看 ThymeleafProperties
源码默认规则
... ...
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
只要我们把 HMTL
页面放在 classpath:/templates/
文件夹下,Thymeleaf
就能自动渲染
测试
在 templates
文件夹中创建 success.html
,创建一个控制器访问
package com.jiker.springbootweb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/success")
public String success(){
//classpath:/templates/success.html
return "success";
}
}
使用语法:
1、导入 thymeleaf
名称空间
2、使用示例
package com.jiker.springbootweb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
@Controller
public class HelloController {
@GetMapping("/success")
public String success(Map map){
map.put("thymeleaf","模板引擎");
//classpath:/templates/success.html
return "success";
}
}
在 html 页面中取出值
Title
success
更多语法示例,详见参考文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf
时间:2019.6.11 20:17