Home  >  Article  >  Java  >  springmvc implements json interaction-requestBody and responseBody (picture and text)

springmvc implements json interaction-requestBody and responseBody (picture and text)

黄舟
黄舟Original
2017-03-16 10:05:412080browse

This article mainly introduces the relevant knowledge of springmvcimplementationjsoninteraction-requestBody and responseBody. Has very good reference value. Let’s take a look at it with the editor

json data interaction

1. Why json data interaction is necessary

The json data format is commonly used in interface calls and html pages. The json format is relatively simple and easy to parse.

For example: webservice interface, transmit json data.

2.springmvc for json interaction

(1 ) requests json and outputs json. The request is a json string, so the requested content needs to be converted into json in the front-end page, which is not convenient.

(2) Request key/value and output json. This method is more commonly used.

3. Environment preparation

3.1 Load the jar package converted from json

Used in springmvc Jackson's package performs json conversion (@requestBody and @responseBody use the following package to perform json conversion), as follows:

jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

@RequestBody Function:

@RequestBody annotation is used to read http requests Content (String), use the HttpMessageConverter interface provided by springmvc to convert the read content into data in json, xml and other formats and bind it to the parameters of the controller method.

This example application:

@RequestBody annotation implements receiving json data of http request and converts json data into javaobject

@ResponseBody function:

This annotation is used to convert the object returned by the Controller method into data in a specified format through the HttpMessageConverter interface, such as: json, xml, etc., and respond to the client through Response

This example application:

@ResponseBody annotation implements converting the object returned by the controller method into a json response to the client

3.2 Configure the json converter

Add messageConverters to the annotation adapter


<!--注解适配器 --> 
 <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>

Note: If you use 463d7d566f84e66ad507872587b9c14c, you do not need to define the above content.

4.json interactive test

4.1 Input json string, the output is json string

4.1.1jspPage

Use the ajax of jquery to submit the json string and parse the output json result .

Don’t forget to introduce jquery-1.4.4.min.js when using jduery


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > 
<title>json交互测试</title> 
 <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script> 
 <script type="text/javascript"> 
  //请求的是json,输出的是json 
  function reuqestJson(){ 
   $.ajax({ 
    type:&#39;post&#39;, 
url:&#39;${pageContext.request.contextPath }/requestJson.action&#39;, 
contentType:&#39;application/json;charset=utf-8&#39;,  
    //数据格式是json串,商品信息 
    data:&#39;{"name":"手机","price":999}&#39;, 
    success:function(data){//返回json结果 
     alert(data); 
    } 
   }); 
  } 
 </script> 
 </head> 
 <body> 
 <input type="button" onclick="reuqestJson()" value="请求的是json,输出的是json"/> 
 </body> 
</html>

4.1.2controller


package cn.edu.hpu.ssm.controller; 
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;
import cn.edu.hpu.ssm.po.ItemsCustom; 
//json交互测试 
@Controller 
public class JsonText { 
 //请求json(商品信息),输出json(商品信息) 
 //@RequestBody将请求的商品信息的json串转成itemsCustom对象 
 //@ResponseBody将itemsCustom转成json格式输出 
 @RequestMapping("/requestJson") 
 public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){ 
  //@ResponseBody将itemsCustom转成json格式输出 
  return itemsCustom; 
 } 
}

4.1.3 Test results

4.2 Input key/value, the output is a json string

4.2.1jsp page

Use jquery's ajax to submit the key/value string and parse the output json result.


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > 
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" > 
 <title>json交互测试</title> 
 <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script> 
 <script type="text/javascript"> 
  //请求是key/value,输出是json 
  function responseJson(){ 
   $.ajax({ 
     type:&#39;post&#39;, 
url:&#39;${pageContext.request.contextPath }/responseJson.action&#39;, 
     //请求的是key/value,这里不需要指定contentType,因为默认就是key/value类型 
     //contentType:&#39;application/json;charset=utf-8&#39;, 
     //数据格式是json串,商品信息 
     data:&#39;name=手机&price=999&#39;, 
     success:function(data){//返回json结果 
      alert(data); 
     } 
    }); 
  } 
 </script> 
 </head> 
 <body> 
 <input type="button" onclick="requestJson()" value="请求的是key/value,输出的是json"/> 
 </body> 
</html>

4.2.2controller


package cn.edu.hpu.ssm.controller; 
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;
import cn.edu.hpu.ssm.po.ItemsCustom; 
//json交互测试 
@Controller 
public class JsonText { 
 //请求key/value(商品信息),输出json(商品信息) 
 @RequestMapping("/responseJson") 
 public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){ 
  //@ResponseBody将itemsCustom转成json格式输出 
  System.out.println("前台传过来得商品名:"+itemsCustom.getName()); 
  return itemsCustom; 
 } 
}

4.2.3 Test

The background console outputs "the product name passed from the front desk: mobile phone", and you can see the feedback of json data by viewing the http data.

The above is the detailed content of springmvc implements json interaction-requestBody and responseBody (picture and text). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn