1、引用maven包
<!-- ThymeLeaf 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、配置文件
###ThymeLeaf配置
spring:
thymeleaf:
#模板的模式,支持 HTML, XML TEXT JAVASCRIPT
mode: HTML5
#编码 可不用配置
encoding: UTF-8
#内容类别,可不用配置
content-type: text/html
#开发配置为false,避免修改模板还要重启服务器
cache: false
#配置模板路径,默认是templates,可以不用配置
prefix: classpath:/templates/
3、创建静态目录templates
4、test.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<script src="./js/jquery-3.4.1.min.js"></script>
<body>
<button type="button" onclick="test()">提交</button>
<div id="message"></div>
</body>
<script>
function test(){
$.ajax({
type : "GET",
dataType: "json", //通过GET方式上传请求,如果接口返回的数据类型为string,这里要改为"text"
// data : data, //上传的参数
async: false ,
url : "http://localhost:8061/api/test", //请求的url。与后端@Request Mapping注解中的值一致。
success: function(result) {
debugger;
console.log(result);//请求成功的回调函数
$("#message").html(result.key1);
}
});
};
</script>
</html>
5、thymeleaf是通过view model的原理跳转的,必须有个controller做为跳转路径:localhost:8081/test
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ViewController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(){
return "test";
}
}
6、test.html中ajax调用的json数据的接口controller
@RestController
@RequestMapping("/api")
public class TestController {
@GetMapping("/test")
public Map<String,String> start(){
Map<String,String> map =new HashMap<>();
map.put("key1","value1");
return map;
};
}
至此完毕,注意点:viewcontroller的返回数据类型必须是string