环境说明
1、springboot 1.5.2
2、thymeleaf 3.0.2
3、idea 2017.3.5
搭建步骤
1、创建maven项目
并添加依赖:
<parent>
<artifactId>agentservices</artifactId>
<groupId>com.nmm.apm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>webview</artifactId>
<properties>
<thymeleaf.version> 3.0.2.RELEASE </thymeleaf.version>
<thymeleaf-layout-dialect.version> 2.1.1 </thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
说明:spring-boot-starter-thymeleaf已经包含了spring-boot-starter-web,因此我们就不需要自己引入了。
properteis:指定了thymeleaf的版本,覆盖了springboot中默认的版本。
2、修改配置文件
在resources目录下创建application.yml,增加如下配置:
spring:
application:
name: webview
thymeleaf:
mode: HTML
encoding: UTF-8
contentType: text/html
cache: false
主要的是cache,指定其不缓存,便于实时刷新,其他用默认配置就好。
thymeleaf的默认模板位置在templates,我们也可以在配置文件中指定前缀。除非存在框架冲突,一般不做修改。
3、创建templates目录
新建index/index.html页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<form action="/login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"/></td>
</tr>
</table>
</form>
</body>
</html>
其中。http://wwww.thymeleaf.org指定了thymeleaf的名称空间。这里我们并没有使用thymeleaf的东西,只是做一些基本环境搭建。
4、创建controller,并跳转:
@RequestMapping("/")
public String index(Model model) {
return "index/index";
}
注意,这里controller使用@controller注解,不要使用@RestController,也不用在方法注解中添加@ResponseBody。加了这两种注解中的任一一种都会将结果作为字符串输出,而不是跳转。
到这一步,就完成了,然后,我们创建入口类,启动服务访问
http://localhost:9000即可看到登录页面。
问题说明
有可能不能跳转页面,常见原因有:
1、模板文件目录不正确
2、使用了@RestController注解,或者@ResponseBody
3、pom文件中没有设置properties,指定thymeleaf版本。