整体的文件结构是这样的,其中重点注意src -> main -> java 路径下的主应用程序。
注意,建立Controller类放置的位置必须和应用程序在同一包内,但是有需要第一个层级:
比如这里,主应用程序时ThymeleaftestApplication.java,它在com.mytest.thymeleaftest包内,
而MyController和MyStringController在com.mytest.thymeleaftest包内的子包controller内,
切记,否则会因为系统扫描不到而被忽略,从而导致失效出错。
以下面这种方式,无需额外设置,直接就能运行。
详细步骤:
第一步,使用Spring Assistant新建项目;
设置好项目名称和包名;
记得勾选 Web -> Web 还有 Template Engines -> Thymeleaf 这两个依赖工具
各部分关键代码:
主应用程序:
package com.mytest.thymeleaftest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ThymeleaftestApplication {
public static void main(String[] args) {
SpringApplication.run(ThymeleaftestApplication.class, args);
}
}
路由控制程序:
这个可以访问模板网页,并将数据在前后端传递:
package com.mytest.thymeleaftest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
//使用@Controller时,@RequestMapping会将返回的字符串当做文件名处理
//使用@RestController时,@RequestMapping会将返回的字符串会直接插入到空白网页输出
@Controller
public class MyController {
@RequestMapping("/template")
public String template(Model model){
//Model model是个连接前后端的模型类
//数据类
Person single=new Person("Bill Gates 比尔 盖茨",55);
//把数据类绑定到模型上
model.addAttribute("ppp",single);
return "template";
}
}
这个直接将字符串输出到前端:
package com.mytest.thymeleaftest.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//使用@Controller时,@RequestMapping会将返回的字符串当做文件名处理
//使用@RestController时,@RequestMapping会将返回的字符串会直接插入到空白网页输出
@RestController
public class MyStringController {
@RequestMapping("/hello")
public String hello(){
return "this is a string from @RestController MyStringController by /hello";
}
}
这个是一个示例数据类,Thymeleaf可以将数据绑定到模板对象:
package com.mytest.thymeleaftest.controller;
import sun.rmi.server.InactiveGroupException;
public class Person {
private String name;
private Integer age;
public String getName(){
return name;
}
public Integer getAge(){
return age;
}
public void setName(String name){
this.name=name;
}
public void setAge(Integer age){
this.age=age;
}
public Person(String name,Integer age){
setName(name);
setAge(age);
}
}
在resources -> static 文件夹内放置默认首页index.html,这样在浏览器内输入主机地址就会默认显示这一个网页:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
this is a static index page
</body>
</html>
resources -> templates文件夹内放置模板网页,比如这里的template.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
this is my template web page
<hr/>
Name:
<input type="text" name="userName" value="James Carrot" th:value="${ppp.name}" />
<br/>
Age:
<input type="text" name="userAge" value="25" th:value="${ppp.age}" />
</body>
</html>