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

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

Mar 16, 2017 am 10:05 AM

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
Copy after login

@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>
Copy after login

Note: If you use , 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>
Copy after login

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; 
 } 
}
Copy after login

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>
Copy after login

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; 
 } 
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

See all articles