springmvc的json数据交互
环境准备
所需jar包除此之外还得有jQuery的js包
代码
product类
package jsonTest;
/**
* Created by Administrator on 2018/10/24.
*/
public class product {
private String name;
private double price;
public product() {
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "product{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
package jsonTest;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Administrator on 2018/10/24.
*/
@Controller
public class json {
@RequestMapping("/sendJson.do")
public @ResponseBody product sendJson(@RequestBody product p){
System.out.println(p);
p.setName("改写后的商品");
p.setPrice(100);
return p;
}
}
<!--处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/10/24
Time: 21:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>JSON与SpringMvc数据交互</title>
<script src="/jQuery/jquery-1.4.4.min.js"></script>
<script>
function sendJson(){
$.ajax({
type:"post",
url:"${pageContext.request.contextPath }/sendJson.do",
contentType:"application/json;charset=utf-8",
data:'{"name":"测试商品","price":99.9}',
success:function(data){
alert(data.name);
}
});
}
</script>
</head>
<body>
<input type="button" value="sendJson" onclick="sendJson()" />
</body>
</html>
还没有评论,来说两句吧...