处理静态资源
我们一般将静态资源放在项目的如下三个位置:
1.resources文件夹下新建一个resources文件夹(classpath:/resources)
2.resources文件夹下新建一个static文件夹
(classpath:/static)
3.resources文件夹下新建一个public文件夹
(classpath:/public)
优先级:1>2(默认)>3
定制首页
只要将首页的"index.html"放在上述的三个位置下,那么访问localhost:8080的时候就会自动跳转主页。
也可以把这个文件放在resources的templates文件夹下,但是这需要controller和thymeleaf模板引擎来共同完成。
thymeleaf
引入依赖:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
我们把需要展现的html文件放在templates文件夹下,然后用controller来调用就行。
如果我们在templates文件夹下写了一个a.html,则controller中可以这么写:
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/ask")
public String e(){
return "a";
}
}
注意这里不是@RestController而是@Controller。
但是要真正使用themeleaf,我们要先导入命名空间。
xmlns:th=“http://www.thymeleaf.org”
所有的html元素都被themeleaf接管,只要使用th:元素名即可。
一个简单的例子:
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/ask")
public String e(Model model){
model.addAttribute("msg","myMessage");
return "a";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th=“http://www.thymeleaf.org”>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>
可以发现在controller中的模板注入的msg,在a.html中可以显现出来了。
1.text与utext
utext会进行转义。
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/ask")
public String e(Model model){
model.addAttribute("msg","<h1>myMessage</h1>");
return "a";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th=“http://www.thymeleaf.org”>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
</body>
</html>
可以发现上面的div就是原本的字符串,而下面的会进行具体的解析。
2.展示数组
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/ask")
public String e(Model model){
model.addAttribute("list", Arrays.asList("a","b","c"));
return "a";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th=“http://www.thymeleaf.org”>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:each="e:${list}" th:text="${e}"></div>
</body>
</html>
或者:
<!DOCTYPE html>
<html lang="en" xmlns:th=“http://www.thymeleaf.org”>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:each="e:${list}">[[${e}]]</div>
</body>
</html>