温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringMVC如何转换JSON数据

发布时间:2021-11-24 10:56:36 来源:亿速云 阅读:311 作者:小新 栏目:开发技术

小编给大家分享一下SpringMVC如何转换JSON数据,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

SpringMVC提供了处理JSON格式请求/响应的        HttpMessageConverter:MappingJackson2HttpMessageConverter。利用Jackson开源类包处理JSON格式的请求或响应消息。

我们需要做的:

  1. 在Spring容器中为RequestmappingHandlerAdapter装配处理JSON的HttpMessageConverter

  2. 在交互过程中请求Accept指定的MIME类型

org.springframework.web.bind.annotation.RequestBody注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把响应的数据绑定到Controller中的方法的参数上。

数据编码格式由请求头的ContentType指定。它分为以下几种情况:

1.application/x-www-form-urlencoded,这种情况的数据@RequestParam、@ModelAttribute也可以处理,并且很方便,当然@RequestBody也可以处理。

2.multipart/form-data,@RequestBody不能处理这种数据格式的数据。

3.application/json、application/xml等格式的数据,必须使用@RequestBody来处理。

在实际开发当中使用@RequestBody注解可以方便的接收JSON格式的数据,并将其转换为对应的数据类型。

DEMO:接收JSON格式的数据:

1.index.jsp

testRequestBody函数发送异步请求到“json/testRequestBody”,其中:contentType:"application/json"表示发送的内容编码格式为json格式,data:JSON.stringify(....)表示发送一个json数据;请求成功后返回一个json数据,接收到返回的json数据后将其设置到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格式的数据</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("数据发送失败!");
			}
		});
	}

</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方法中的第一个参数@RequestBody Book book,使用@RequestBody注解获取到json数据,将json数据设置到对应的Book对象的属性中。第二个参数是HttpServletResponse对象,用来输出响应数据到客户端。

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对象转换成json格式的数据。
		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分发请求所必须的,并提供了数据帮顶支持、@NumberFormatannotation支持、@DateTimeFormat支持、@Valid支持、读写XML的支持一记读写JSON的支持等功能。本例处理ajax请求就用到了对JSON功能的支持。

(2)<mvc:default-servlet-handler/>使用默认的Servlet来响应静态文件,因为在web.xml中使用了DispatcherServlet截获所有请求的url,而本例引入的js/jquery-1.11.0.min.js以及js/json2.js文件的时候,DispatcherServlet会将"/"看成请求路径,就会报404的错误。而当配置文件加上这个默认的Servlet时,Servlet在找不到它时会去找静态的内容。

<?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如何转换JSON数据”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI