@RequestBody:用于接收json串 如ajax请求的data参数 可在直接接收转换到Pojo
@ResponseBody:表示该方法的返回结果直接写入 HTTP response body 中
示例:
1.新建一个maven项目,在pom文件中导入jackson包如图:
maven依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.1</version>
</dependency>
2.配置web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定可以读取到resourcess文件下的路径-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.编写controller层
import com.blb.entity.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
//把这个类加到spring中托管
@Controller
@RequestMapping("user")
public class Demo {
// 表示该方法的返回结构直接写入HTTP ResponseBody中
@ResponseBody
//用于映射请求地址
@RequestMapping("demo")
public String test(@RequestBody User user){
System.out.println(user);
return "hello";
}
4.编写jsp文件,在里面制造数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--导入jquery--%>
<script crossorigin="anonymous" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" src="http://lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
var user ={}
user.id = "1",
user.username="张三",
user.pwd = "123",
$.ajax({
url:'/user/demo',
//请求方式
type:'post',
contentType:"application/json",
//把对象变成json数据
data: JSON.stringify(user),
success:function (e) {
console.log(e)
}
})
})
</script>
</body>
</html>
运行结果: