<p id="ldwvh"></p>

    溫馨提示×

    溫馨提示×

    您好,登錄后才能下訂單哦!

    密碼登錄×
    登錄注冊×
    其他方式登錄
    點擊 登錄注冊 即表示同意《億速云用戶服務條款》

    SpringMVC如何轉(zhuǎn)換JSON數(shù)據(jù)

    發(fā)布時間:2021-11-24 10:56:36 來源:億速云 閱讀:331 作者:小新 欄目:開發(fā)技術

    小編給大家分享一下SpringMVC如何轉(zhuǎn)換JSON數(shù)據(jù),相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

    SpringMVC提供了處理JSON格式請求/響應的        HttpMessageConverter:MappingJackson2HttpMessageConverter。利用Jackson開源類包處理JSON格式的請求或響應消息。

    我們需要做的:

    1. 在Spring容器中為RequestmappingHandlerAdapter裝配處理JSON的HttpMessageConverter

    2. 在交互過程中請求Accept指定的MIME類型

    org.springframework.web.bind.annotation.RequestBody注解用于讀取Request請求的body部分數(shù)據(jù),使用系統(tǒng)默認配置的HttpMessageConverter進行解析,然后把響應的數(shù)據(jù)綁定到Controller中的方法的參數(shù)上。

    數(shù)據(jù)編碼格式由請求頭的ContentType指定。它分為以下幾種情況:

    1.application/x-www-form-urlencoded,這種情況的數(shù)據(jù)@RequestParam、@ModelAttribute也可以處理,并且很方便,當然@RequestBody也可以處理。

    2.multipart/form-data,@RequestBody不能處理這種數(shù)據(jù)格式的數(shù)據(jù)。

    3.application/json、application/xml等格式的數(shù)據(jù),必須使用@RequestBody來處理。

    在實際開發(fā)當中使用@RequestBody注解可以方便的接收JSON格式的數(shù)據(jù),并將其轉(zhuǎn)換為對應的數(shù)據(jù)類型。

    DEMO:接收JSON格式的數(shù)據(jù):

    1.index.jsp

    testRequestBody函數(shù)發(fā)送異步請求到“json/testRequestBody”,其中:contentType:"application/json"表示發(fā)送的內(nèi)容編碼格式為json格式,data:JSON.stringify(....)表示發(fā)送一個json數(shù)據(jù);請求成功后返回一個json數(shù)據(jù),接收到返回的json數(shù)據(jù)后將其設置到span標簽中

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>測試json格式的數(shù)據(jù)</title>
    <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="js/json2.js"></script>
    <script type="text/javascript">
    	$(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:"老人與海"}),
    			async:true,
    			success:function(data){
    				alert("成功");
    				alert(data);
    				console.log(data);
    				$("#id").html(data.id);
    				$("#name").html(data.name);
    				$("#author").html(data.author);
    				
    			},
    			error:function(){
    				alert("數(shù)據(jù)發(fā)送失敗!");
    			}
    		});
    	}
    
    </script>
    </head>
    <body>
    	編號:<span id="id"></span>
    	書名:<span id="name"></span>
    	作者:<span id="author"></span>
    </body>
    </html>

    2.Book實體類

    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

    setJson方法中的第一個參數(shù)@RequestBody Book book,使用@RequestBody注解獲取到json數(shù)據(jù),將json數(shù)據(jù)設置到對應的Book對象的屬性中。第二個參數(shù)是HttpServletResponse對象,用來輸出響應數(shù)據(jù)到客戶端。

    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{
    		//注意ObjectMapper類是Jackson庫的主要類。負責將java對象轉(zhuǎn)換成json格式的數(shù)據(jù)。
    		ObjectMapper mapper = new ObjectMapper();
    		logger.info(mapper.writeValueAsString(book));
    		book.setAuthor("海明威");
    		response.setContentType("application/json;charset=UTF-8");
    		response.getWriter().println(mapper.writeValueAsString(book));
    	}
    }

    4.springmvc-config

     (1)<mvc:annotation-drive>會自動注冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean,這是SpringMVC為@Controllers分發(fā)請求所必須的,并提供了數(shù)據(jù)幫頂支持、@NumberFormatannotation支持、@DateTimeFormat支持、@Valid支持、讀寫XML的支持一記讀寫JSON的支持等功能。本例處理ajax請求就用到了對JSON功能的支持。

    (2)<mvc:default-servlet-handler/>使用默認的Servlet來響應靜態(tài)文件,因為在web.xml中使用了DispatcherServlet截獲所有請求的url,而本例引入的js/jquery-1.11.0.min.js以及js/json2.js文件的時候,DispatcherServlet會將"/"看成請求路徑,就會報404的錯誤。而當配置文件加上這個默認的Servlet時,Servlet在找不到它時會去找靜態(tài)的內(nèi)容。

    <?xml version="1.0"
     encoding="UTF-8"?>
     <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:mvc="http://www.springframework.org/schema/mvc"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:aop="http://www.springframework.org/schema/aop"
    	xsi:schemaLocation="
    		http://www.springframework.org/schema/beans
    		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    		http://www.springframework.org/schema/context
    		http://www.springframework.org/schema/context/spring-context-4.2.xsd
    		http://www.springframework.org/schema/aop    
        	http://www.springframework.org/schema/aop/spring-aop-4.2.xsd   
        	http://www.springframework.org/schema/mvc
    		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
    		"> 
    	<!-- Spring 可以自動去掃描base-pack下面的包或者子包下面的java文件 -->
    	<!-- 如果掃描到spring相關的注解類,將其注冊為spring的bean -->
    	<context:component-scan base-package="com.cn.controller" />
    	<!-- 設置配置方案 -->
    	<mvc:annotation-driven/>
    	<mvc:default-servlet-handler/>
    	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
    	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix">
    			<value>/WEB-INF/content/</value>
    		</property>
    		<property name="suffix">
    			<value>.jsp</value>
    		</property>
    	</bean>
    	
    </beans>

    需要添加的jar包:Spring的所有jar、commons-logging.jar以及Jackson相關的jar

    需要引入的js:jquery.js、json2.js

    以上是“SpringMVC如何轉(zhuǎn)換JSON數(shù)據(jù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

    AI