Spring Boot Web开发
静态资源处理
-
通过webjars存放静态资源
if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); }
在
WebMvcAutoConfiguration
中写出了静态资源可以存放于特点的位置:- /webjars/**
- /META-INF/resources/webjars/
这里面的内容可以直接访问
-
在
ResourceProperties
中指明了第二个静态资源可以存放的位置private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
- /META-INF/resources/**
- /resources/**
- /static/**
- /public/**
- /**
静态资源可以存放于这些目录之下
-
静态资源的自定义
spring: mvc: static-path-pattern:
首页定制
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
return welcomePageHandlerMapping;
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
在WebMvcAutoConfiguration
中有一个WelcomePageHandlerMapping的Bean,里面是处理首页数据的
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage.get());
setRootViewName("forward:index.html");
}
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}
可见mvc 的自动配置是去静态资源路径下找index.html文件
跳转到首页
需要thymeleaf
模板引擎
把首页放到templates文件夹下
编写Controller
@Controller
public class IndexController {
@RequestMapping("/index")
public String toIndex()
{
return "index";
}
}
thymeleaf 模板引擎
在pom.xml中引入
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
在Thymeleaf的配置中写道
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
Thymeleaf的文件都在template中,后缀为html
thymeleaf语法
引用命名空间
<html xmlns:th="http://www.thymeleaf.org">
输出内容
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
- 使用
th:text
使内容输出到标签中 - #{}用来引用属性
th:utext
不会对转义
访问对象
${param.x} 返回名为x 的 request参数。(可能有多个值)
${session.x} 返回名为x的Session参数。
${application.x} 返回名为 servlet context 的参数。
输出url
<a href="product/list.html" th:href="@{/product/list}">Product List</a>
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
设置Attribute
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> --设置单个
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" /> --一次设置多个
循环输出的语法
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
自定义配置 mvc
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own
@Configuration
class of typeWebMvcConfigurer
but without@EnableWebMvc
.
如果想进一步配置MVC的话,继承 WebMvcConfigurer
并且加上@Configuration
,但是别加@EnableWebMvc
.
@Configuration
public class MVCConfig implements WebMvcConfigurer {
...
}
可以去重写里面的某些方法,改变配置
如果加了@EnableWebMvc
,原来的自动配置不会生效