json数据交互与@RequestBody

﹏ヽ暗。殇╰゛Y 2023-10-18 09:14 102阅读 0赞

@RequestBody

@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。传统的请求参数:
itemEdit.action?id=1&name=zhangsan&age=12
现在的请求参数:
使用POST请求,在请求体里面加入json数据

  1. {
  2. "id": 1,
  3. "name": "测试商品",
  4. "price": 99.9,
  5. "detail": "测试商品描述",
  6. "pic": "123456.jpg"
  7. }

请求json,响应json实现

1.加入jar包

https://download.csdn.net/download/badao_liumang_qizhi/10689053

2.编写action

  1. //json数据交互
  2. @RequestMapping(value = "/json.action")
  3. public @ResponseBody
  4. Items json(@RequestBody Items items){
  5. return items;
  6. }

3.编写model

  1. public class Items {
  2. private Integer id;
  3. private String name;
  4. private Float price;
  5. private String pic;
  6. private Date createtime;
  7. private String detail;
  8. 省略get set方法

3.编写jsp

这里不加触发事件,直接页面加载完就出发,接受到json数据后也不处理,直接返回。

  1. <script type="text/javascript">
  2. $(function(){
  3. var params = '{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';
  4. $.ajax({
  5. url : "${pageContext.request.contextPath }/json.action",
  6. data : params,
  7. contentType : "application/json;charset=UTF-8",//发送数据的格式
  8. type : "post",
  9. dataType : "json",//回调
  10. success : function(data){
  11. alert("获取到的数据的name为:"+data.name);
  12. }
  13. });
  14. });
  15. </script>

4.配置json转换器

如果不使用注解驱动,就需要给处理器适配器配置json转换器。

在springmvc.xml配置文件中,给处理器适配器加入json转换器:

  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>

成功后回调,将传回来的数据赋给形参data,此时data可以直接调用model 的属性。

完成最简单的前后端数据交互。

![Image 1][]70

[Image 1]:

发表评论

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

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

相关阅读