前端视图层
使用axios发送post请求。
<body>
<button onclick="handleClick()">点击测试</button>
<script th:src="@{/static/js/axios.min.js}"></script>
<script th:inline="javascript">
//获取上下文路径
var contextPath = /*[[@{/}]]*/'';
function handleClick(){
axios({
method:"post",
url:contextPath+"test",
data:{
"username":"admin",
"password":"123456"
}
})
}
</script>
</body>
后端控制层
使用@RequestBody接收请求体。
- 控制器方法形参是一个String类型
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test(@RequestBody String request){
System.out.println(request);
return "success";
}
13:50:55.179 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/demo6/test", parameters={}
13:50:55.180 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(String)
13:50:55.206 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read "application/json;charset=UTF-8" to ["{"username":"admin","password":"123456"}"]
{"username":"admin","password":"123456"}
- 控制器方法形参是一个实体类
package com.example.mvc.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
}
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test(@RequestBody User user){
System.out.println(user);
System.out.println(user.getUsername()+","+user.getPassword());
return "success";
}
13:53:17.186 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/demo6/test", parameters={}
13:53:17.189 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(User)
13:53:17.281 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read "application/json;charset=UTF-8" to [User(id=null, username=admin, password=123456)]
User(id=null, username=admin, password=123456)
admin,123456