Spring mvc 前后台通过json交互【转】

原文转自:https://www.cnblogs.com/zhaojiankai/p/8184596.html

本节内容:

  • @RequestBody
  • @ResponseBody
  • 请求json,响应json实现

前端可以有很多语言来写,但是基本上后台都是java开发的,除了c++(开发周期长),PHP和#Net(追求速度,快速开发)这3种也可以写后台。

浏览器和java程序打交道,用jsp、js。

安卓、IOS客户端和Java程序打交道,发送的是JSON字符串。Java程序接收到,解析JSON字符串,形成POJO对象,然后进行业务处理。处理完变成POJO或者包装类对象或者List集合,转成JSON字符串发回给安卓、IOS客户端。

所以掌握了JSON数据交互,就不用关心前端是什么语言开发的了。

一、@RequestBody

作用:
@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。

传统的请求参数:


1

itemEdit.action?id=1&name=zhangsan&age=12

现在的请求参数:使用POST请求,在请求体里面加入json数据


1

2

3

4

5

6

7

{

    "id"1,

    "name""测试商品",

    "price"99.9,

    "detail""测试商品描述",

    "pic""123456.jpg"

}

  

本例子应用:

@RequestBody注解实现接收http请求的json数据,将json数据转换为java对象进行绑定。

二、@ResponseBody

作用:

@ResponseBody注解用于将Controller的方法返回的对象,通过springmvc提供的HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端。

本例子应用:

@ResponseBody注解实现将Controller方法返回java对象转换为json响应给客户端。

三、请求json,响应json实现

1. 加入jar包

如果需要springMVC支持json,必须加入json的处理jar

我们使用Jackson这个jar,如下图:

2. ItemController编写


1

2

3

4

5

6

7

8

9

10

/**

 * 测试json的交互

 * @param item

 * @return

 */

@RequestMapping("/testJson.action")

// @ResponseBody //或者写在这里也可以

public @ResponseBody Items testJson(@RequestBody Items item) {

    return item;

}

3. 使用Postman测试

如果提交表单测试,数据是存在request中,以 key:value 的形式存在。所以使用Postman工具进行测试。或者在写个页面,在页面上写一个ajax,用ajax发送一个json字符串,回调也用json字符串。

4. 编写ajax测试

引入jquery文件:

修改itemList.jsp文件,在页面初始化时利用ajax发送json字符串:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>

<script type="text/javascript">

    $(function(){

        //alert(1);

        //这是json格式,但不是json串,这是key:value,相当于一个map。{}外面得加上一个单引号才是串,但只是个json格式的字符串,不是json数据

        var params = ‘{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}‘;

        /*$.post(url,params,function(data){//这是回调json字符串,不能发送json字符串

        },"json");*/

        $.ajax({

            url: "${pageContext.request.contextPath }/testJson.action",

            data: params,

            contentType: "application/json;charset=UTF-8"//发送数据的格式

            type: "post",

            dataType: "json"//这是返回来是json,也就是回调json

            success: function(data){

                alert(data.name);

            }

        });

    });

</script>

然后IDEA更新下资源:

刷新页面:

5. 配置json转换器

如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器,参考之前学习的自定义参数绑定。

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


1

2

3

4

5

6

7

8

    <!--处理器适配器 -->

<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>

原文地址:https://www.cnblogs.com/langren1992/p/11437939.html

时间: 2024-08-03 19:06:55

Spring mvc 前后台通过json交互【转】的相关文章

Spring MVC 前后台传递json格式数据 Content type &#39;application/x-www-form-urlencoded;charset=UTF-8&#39; not supported

报错如下: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 解决方案: 引入如下包: 问题既解决. Spring MVC 前后台传递json格式数据 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

Spring MVC —— 前后台传递JSON

1. 传递JSON参数 vardata = {'id':1,'name':'abc'}; $.ajax({ type:'post', url:'homePageAction.do?testAJax', contentType:'application/x-www-form-urlencoded', data:JSON.stringify(data), success:function(data){ console.log(data.msg); }, error:function(){ } });

spring mvc 和ajax异步交互完整实例(转自CSDN) 附下载地址

spring mvc 和ajax异步交互完整实例 spring MVC 异步交互demo: demo下载地址:http://download.csdn.net/download/quincylk/9521375 1.jsp页面: [java] view plain copy print? <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-

IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践

最近把编辑器换成IntelliJ IDEA,主要是Eclipse中处理Maven项目很不方便,很早就听说IntelliJ IDEA的大名了,但是一直没机会试试.最近终于下载安装了,由于是新手,决定尝试个Tutorials,最终找了个熟悉点的项目,就是Getting Started with Spring MVC, Hibernate and JSON(http://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with

[转]Spring MVC 学习笔记 json格式的输入和输出

Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用 <!-- json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.8.1</version>

IntelliJIDEA Getting+Started+with+Spring+MVC,+Hibernate+and+JSON

https://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC,+Hibernate+and+JSON In this tutorial we will create a simple web application using Spring MVC, Hibernate and JSON. We will use Maven to manage dependencies and Inte

spring mvc+ajax 实现json格式数据传递

使用ajax传递JSON对象 下面示例为ajax发送json对象,返回json格式数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 $.ajax({ url: "api/user", type: "POST", timeout: txnTimeOut, async: true, dataType: "json", data: {username : "lucy"}

spring mvc 和ajax异步交互完整实例

Spring MVC 异步交互demo: 1.jsp页面: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR

Spring MVC前后端数据交互总结

控制器 作为控制器,大体的作用是作为V端的数据接收并且交给M层去处理,然后负责管理V的跳转.SpringMVC的作用不外乎就是如此,主要分为:接收表单或者请求的值,定义过滤器,跳转页面:其实就是servlet的替代品. - append Spring MVC在Web应用中扮演V的角色,负责处理HTTP请求并返回相应的资源,它在用的时候要配置一个核心的Dispatcher负责检查资源,请求过来的时候会查找是否有相应的Handler,有就会把请求交给Controller,一般使用注解来配置暴露给用户