本文的示例代码参考ResponseX
目录
开始
spring init -dweb,thymeleaf --build gradle ResponseX
# cd ResponseX
vim src/main/java/com/example/ResponseX/UserController.java
package com.example.ResponseX;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
@RequestMapping("/users")
public class UserController {
@GetMapping
public String getUsers() {
return "getUsers";
}
}
使用@ResponseBody
- 测试
./gradlew bootrun
curl -x 127.0.0.1:8888 localhost:8080/users # 返回"getUsers"
此时 HTTP请求的抓包信息如下
这里使用Charles抓包工具 更多参考 Charles 从入门到精通
删除@ResponseBody
sed -i "" '/@ResponseBody/d' src/main/java/com/example/ResponseX/UserController.java
- 测试
./gradlew bootrun
curl -x 127.0.0.1:8888 localhost:8080/users # 返回"getUsers"
此时 HTTP请求的抓包信息如下
vim src/main/resources/templates/getUsers.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>getUsers</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>hi, getUsers</h1>
</body>
</html>
- 测试
./gradlew bootrun
curl -x 127.0.0.1:8888 localhost:8080/users
此时 HTTP请求的抓包信息如下