springmvc的json数据交互

ゝ一世哀愁。 2022-05-13 14:48 377阅读 0赞

环境准备

所需jar包
在这里插入图片描述除此之外还得有jQuery的js包

代码

product类

  1. package jsonTest;
  2. /**
  3. * Created by Administrator on 2018/10/24.
  4. */
  5. public class product {
  6. private String name;
  7. private double price;
  8. public product() {
  9. }
  10. public double getPrice() {
  11. return price;
  12. }
  13. public void setPrice(double price) {
  14. this.price = price;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. @Override
  23. public String toString() {
  24. return "product{" +
  25. "name='" + name + '\'' +
  26. ", price=" + price +
  27. '}';
  28. }
  29. }
  30. package jsonTest;
  31. import org.springframework.stereotype.Controller;
  32. import org.springframework.web.bind.annotation.RequestBody;
  33. import org.springframework.web.bind.annotation.RequestMapping;
  34. import org.springframework.web.bind.annotation.RequestParam;
  35. import org.springframework.web.bind.annotation.ResponseBody;
  36. /**
  37. * Created by Administrator on 2018/10/24.
  38. */
  39. @Controller
  40. public class json {
  41. @RequestMapping("/sendJson.do")
  42. public @ResponseBody product sendJson(@RequestBody product p){
  43. System.out.println(p);
  44. p.setName("改写后的商品");
  45. p.setPrice(100);
  46. return p;
  47. }
  48. }
  1. <!--处理器适配器 -->
  2. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  3. <property name="messageConverters">
  4. <list>
  5. <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  6. </list>
  7. </property>
  8. </bean>
  9. <%--
  10. Created by IntelliJ IDEA.
  11. User: Administrator
  12. Date: 2018/10/24
  13. Time: 21:07
  14. To change this template use File | Settings | File Templates.
  15. --%>
  16. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  17. <html>
  18. <head>
  19. <title>JSON与SpringMvc数据交互</title>
  20. <script src="/jQuery/jquery-1.4.4.min.js"></script>
  21. <script>
  22. function sendJson(){
  23. $.ajax({
  24. type:"post",
  25. url:"${pageContext.request.contextPath }/sendJson.do",
  26. contentType:"application/json;charset=utf-8",
  27. data:'{"name":"测试商品","price":99.9}',
  28. success:function(data){
  29. alert(data.name);
  30. }
  31. });
  32. }
  33. </script>
  34. </head>
  35. <body>
  36. <input type="button" value="sendJson" onclick="sendJson()" />
  37. </body>
  38. </html>

发表评论

表情:
评论列表 (有 0 条评论,377人围观)

还没有评论,来说两句吧...

相关阅读