Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How SpringMVC converts JSON data

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how SpringMVC converts JSON data, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

SpringMVC provides HttpMessageConverter:MappingJackson2HttpMessageConverter for handling requests / responses in JSON format. Use Jackson open source class packages to process request or response messages in JSON format.

What we need to do:

Processing JSON's HttpMessageConverter for RequestmappingHandlerAdapter assemblies in a Spring container

Request the MIME type specified by Accept during the interaction

The org.springframework.web.bind.annotation.RequestBody annotation is used to read the body part of the Request request, parse it using the default HttpMessageConverter configured by the system, and then bind the response data to the parameters of the method in Controller.

The data encoding format is specified by the ContentType of the request header. It is divided into the following situations:

1.application/x-www-form-urlencoded, the data in this case can also be handled by @ RequestParam and @ ModelAttribute, and it is very convenient, of course, @ RequestBody can also be handled.

2. Multipartposition form data can not handle data in this data format.

Data in 3.application/json, application/xml, and other formats must be processed using @ RequestBody.

In actual development, using @ RequestBody annotation can easily receive data in JSON format and convert it to the corresponding data type.

DEMO: receives data in JSON format:

1.index.jsp

The testRequestBody function sends an asynchronous request to "json/testRequestBody", where: contentType: "application/json" indicates that the content is encoded in json format, and data:JSON.stringify (....) Indicates that a json data is sent; if the request is successful, a json data is returned. After receiving the returned json data, set it to the span tag.

Test data in json format $(document) .ready (function () {testRequestBody ();}) Function testRequestBody () {$.ajax ({url: "${pageContext.request.contextPath} / json/testRequestBody", dateType: "json", type: "post", contentType: "application/json" Data:JSON.stringify ({id:1,name: "Old Man and the Sea"}), async:true, success:function (data) {alert ("success") Alert (data); console.log (data); $("# id") .html (data.id); $("# name") .html (data.name) $("# author") .html (data.author);}, error:function () {alert ("data transmission failed!") ;}});} No.: title: author:

2.Book entity class

Package com.cn.domain;import java.io.Serializable;public class Book implements Serializable {private Integer id; private String name; private String author; public Book () {super ();} public Book (Integer id, String name, String author) {super (); this.id = id This.name = name; this.author = author;} public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getName () {return name } public void setName (String name) {this.name = name;} public String getAuthor () {return author;} public void setAuthor (String author) {this.author = author;}}

3.BookController

The first parameter in the setJson method, @ RequestBody Book book, gets the json data using the @ RequestBody annotation, and sets the json data to the properties of the corresponding Book object. The second parameter is the HttpServletResponse object, which is used to output response data to the client.

Package com.cn.controller;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import com.cn.domain.Book;import com.fasterxml.jackson.databind.ObjectMapper;@Controller@RequestMapping ("/ json") public class BookController {private static final Log logger = LogFactory.getLog (BookController.class) @ RequestMapping (value= "/ testRequestBody") public void setJson (@ RequestBody Book book, HttpServletResponse response) throws Exception {/ / Note that the ObjectMapper class is the main class of the Jackson library. Responsible for converting java objects into data in json format. ObjectMapper mapper = new ObjectMapper (); logger.info (mapper.writeValueAsString (book)); book.setAuthor (Hemingway); response.setContentType ("application/json;charset=UTF-8"); response.getWriter () .println (mapper.writeValueAsString (book));}}

4.springmvc-config

(1) automatically register RequestMappingHandlerMapping and RequestMappingHandlerAdapter Bean, which is necessary for SpringMVC to distribute requests for @ Controllers, and provide data support, @ NumberFormatannotation support, @ DateTimeFormat support, @ Valid support, read-write XML support, read-write JSON support and other functions. In this example, support for JSON functionality is used to handle ajax requests.

(2) use the default Servlet to respond to static files, because DispatcherServlet is used in web.xml to intercept all requested url, and when the js/jquery-1.11.0.min.js and js/json2.js files introduced in this example, DispatcherServlet will regard "/" as the request path and will report a 404 error. When the default Servlet is added to the configuration file, Servlet will look for static content when it cannot be found.

/ WEB-INF/content/ .jsp

Jar packages to be added: all jar, commons-logging.jar and Jackson-related jar of Spring

Js:jquery.js and json2.js to be introduced

The above is all the content of the article "how SpringMVC converts JSON data". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report