Jsp在内嵌的servlet容器上运行有一些问题(内嵌tomcat、jetty不支持以jar形式运行jsp,undertow不支持jsp)
Spring boot提供了大量模板引擎,包含FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,springBoot推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的springMVC支持。
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.添加controller
和jsp的没什么两样
@RequestMapping("/toLogin")
public String toLogin(){
return "user/login";
}
但jsp是通过配置前缀和后缀去找相应的jsp文件。
Themeleaf默认是从classpath:/templates/找.html文件
源码中有说:
因此需要在templates目录下创建user目录,并添加login.html文件;
添加一个首页:
注:确保templates添加到classpath。
3.创建login.html文件
html文件,需要加入Themeleaf头。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot and Thymeleaf example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h3>Spring Boot and Thymeleaf</h3>
<p>Hello World!</p>
<form action="doLogin" method="post">
<p><input type="text" name="username" placeholder="请输入用户名"/></p>
<p><input type="password" name="password" placeholder="请输入密码"/></p>
<p><input type="submit" value="登录"/></p>
</form>
</body>
</html>
4.访问
Main启动项目,访问:
后台输出:User(username=gary, password=123)