SpringMVC已经提供了JSON交互的功能,只需要用就行了,但是需要导包
@RequestBody
作用:
@RequestBody注解用于读取HTTP请求的内容(JSON字符串)
通过SpringMVC提供HttpMessageConveter接口将读到的内容(JSON字符串)转换为Java对象
并绑定到Controller方法的参数上
@ReponseBody
作用:
@ReponseBody注解用于将Controller的方法 的返回的对象(Java对象)
通过Spring提供的HttpMessageConveter接口将数据转成 指定的 数据格式(JSON、xml)
通过response相应给客户端
案例
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script src="../lib/jquery-1.9.1.min.js">
</script>
<script>
var product = {
id:10,
name:"荣耀30",
price:999,
createTime:"2019-06-16 10:35:00",
detail:"啊,好用啊"
};
$.ajax({
url:"/test/testAjax.action",
data:JSON.stringify(product),
type:"POST",
contentType:"application/json;charset=utf-8",
success:function (data) {
console.log(data);
},
error:function (error) {
console.log("error:"+error);
}
});
</script>
</html>
后端代码:
package com.hxy.controller;
import com.hxy.pojo.Product;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestAjaxController {
@RequestMapping(value = "/test/testAjax.action")
@ResponseBody
public Product testAjax(@RequestBody Product product){
System.out.println(product);
Product product1 = new Product();
product1.setId(22);
product1.setName("啦啦啦");
return product1;
}
}
SpringMVC配置文件,进行时间格式转换String->Date
<!--注解驱动,配置时间转换格式-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>test/json;charset=utf-8</value>
</list>
</property>
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"></constructor-arg>
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>