静态资源访问
静态资源:js, css, html, 图片,音视频等
静态资源路径:是指系统可以直接访问的路径,且路径下的所有文件均可被用户直接读取。
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
案例:在classpath下面创建static目录,并且加入一个图片a.png
加入之后,然后不需要重启直接访问:http://localhost:8081/a.png
修改默认的静态资源目录:spring.resources.static-locations
模板引擎
Spring Boot强烈建议使用模板引擎渲染html页面,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性。
在这里讲两种模板引擎的集成:Thymeleaf(spring boot推荐), FreeMarker
Thymeleaf
Spring boot默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径
集成Thymeleaf步骤:
1.修改pom.xml, 增加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.编写Controller
@Controller
public class SampleController {
@RequestMapping("/testThymeleaf")
public String testThymeleaf(ModelMap map) {
// 设置属性
map.addAttribute("name", "zhangsan");
// testThymeleaf:为模板文件的名称
// 对应src/main/resources/templates/testThymeleaf.html
return "testThymeleaf";
}
}
3.在src/main/resources/下面建立templates/testThymeleaf.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>testThymeleaf</title>
</head>
<body>
<h1 th:text="${name}">ABC</h1>
</body>
</html>
4.运行spring boot,浏览器输入:http://localhost:8081/testThymeleaf
Thymeleaf的默认参数配置(供参考):
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true
# Enable template caching.
spring.thymeleaf.cache=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.content-type=text/html
# Template encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names=
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html
# Order of the template resolver in the chain.
spring.thymeleaf.template-resolver-order=
# Comma-separated list of view names that can be resolved.
spring.thymeleaf.view-names=
FreeMarker
1.修改pom.xml,增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.写Controller
@RequestMapping("/testFreemarker")
public String testFreemarker(Map<String,String> map) {
map.put("name", "张三");
return "hello"; //默认为src/main/resources/templates/hello.flt
}
3.hello.flt,目录为:src\main\resources\templates
<html>
<body>
hello, ${name}
</body>
</html>
4.运行spring boot main,浏览器输入如下地址:http://localhost:8081/testFreemarker
更多springboot相关知识参见[持续更新]