`

Spring整合JSON之@RequestBody和@ResponseBody

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2318017

 

Reference

@RequestBody 

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestbody

@ResponseBody

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-responsebody

 

Project Directory

Maven Dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.fool</groupId>
	<artifactId>springmvc</artifactId>
	<name>springmvc</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<org.springframework-version>4.2.7.RELEASE</org.springframework-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.1</version>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.10</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.3.11.v20160721</version>
				<configuration>
					<scanIntervalSeconds>10</scanIntervalSeconds>
					<httpConnector>
						<port>8888</port>
					</httpConnector>
					<webApp>
						<contextPath>/springmvc</contextPath>
					</webApp>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app> 

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		
</beans>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources 
		directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<context:component-scan base-package="org.fool.springmvc" />

</beans:beans>

User.java

package org.fool.springmvc;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class User {
	private Long id;
	private String username;
	private String password;

	public User() {
	}

	public User(Long id, String username, String password) {
		this.id = id;
		this.username = username;
		this.password = password;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

UserController.java

package org.fool.springmvc;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

@Controller
@RequestMapping("/user")
public class UserController {
	
	public static Map<Long, User> userMap;
	
	static {
		userMap = Maps.newHashMap();
		userMap.put(10086L, new User(100086L, "hello", "world"));
		userMap.put(10087L, new User(100086L, "hey", "girl"));
		userMap.put(10088L, new User(100086L, "love", "me"));
		
	}
	
	@RequestMapping(value = "/testresponsebody/{id}", method = RequestMethod.GET)
	@ResponseBody
	public User testResponseBody(@PathVariable Long id) {
		User user = userMap.get(id);
		System.out.println(user);
		return user;
	}
	
	@RequestMapping(value = "/testrequestbody", method = RequestMethod.POST)
	@ResponseBody
	public User testRequestBody(@RequestBody User user) {
		System.out.println(user);
		return user;
	}
	
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index JSP</title>
<script type="text/javascript" src="resources/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#responsebody").click(function() {
			responseBody();
		});
		$("#requestbody").click(function() {
			requestBody();
		});
	});

	function responseBody() {
		var url = 'http://localhost:8888/springmvc/user/testresponsebody/';
		var params = $('#id-select').val();
		url += params;
		alert(url);

		var args = {};

		$.get(url, args, function(data) {
			alert("id: " + data.id + "\nusername: " + data.username + "\npassword: " + data.password);
		});
	}

	function requestBody() {
		var url = 'http://localhost:8888/springmvc/user/testrequestbody';
		var data = '{"id":"' + $('#id').val() + '","username":"' + $('#username').val() + '","password":"'
				+ $('#password').val() + '"}';

		alert(data);

		$.ajax({
			url : url,
			data : data,
			type : "POST",
			dataType : 'json',
			contentType : 'application/json',
			success : function(data) {
				alert("id: " + data.id + "\nusername: " + data.username + "\npassword: " + data.password);
			},
			error : function() {
				alert('Error...');
			}
		});
	}
</script>
</head>
<body>
	<table>
		<tr>
			<td>id</td>
			<td>
				<select id="id-select">
					<option value="10086">10086</option>
					<option value="10087">10087</option>
					<option value="10088">10088</option>
				</select>
			</td>
		</tr>
		<tr>
			<td><input type="button" id="responsebody" value="test ResponseBody - GET" /></td>
		</tr>
	</table>

	<table>
		<tr>
			<td>id</td>
			<td><input id="id" value="10000"/></td>
		</tr>
		<tr>
			<td>username</td>
			<td><input id="username" value="Mr"/></td>
		</tr>
		<tr>
			<td>password</td>
			<td><input id="password" value="Big"/></td>
		</tr>
		<tr>
			<td><input type="button" id="requestbody" value="test RequestBody - POST" /></td>
		</tr>
	</table>
</body>
</html>

mvn jetty:run


 

Verify Result

http://localhost:8888/springmvc/index.jsp


 Click button 'test ResponseBody - GET'


 查看Response


 查看Console输出


 

 Click button 'test RequestBody - POST'


 查看Response


  查看Console输出


 

 

 

  • 大小: 21.3 KB
  • 大小: 187.8 KB
  • 大小: 86.6 KB
  • 大小: 141.3 KB
  • 大小: 14.8 KB
  • 大小: 35.2 KB
  • 大小: 143.2 KB
  • 大小: 16.3 KB
  • 大小: 33 KB
分享到:
评论

相关推荐

    Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable

    例如,你可以结合使用`@RequestBody`和`@ResponseBody`来创建一个接收JSON数据并返回JSON响应的方法,同时利用`@PathVariable`处理URL中的动态部分,实现灵活的路由控制。 在实际开发中,我们还需要了解如何配置...

    浅析@ReponseBody和@RequestBody注解

    浅析@ReponseBody和@RequestBody注解 @ReponseBody和@RequestBody是Spring MVC框架中两个重要的注解,分别用于处理HTTP请求和响应体。下面我们将详细分析这两个注解的作用和Spring MVC内部是如何对他们进行解析的。...

    SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(上)

    在实际开发中,`@RequestBody` 和 `@ResponseBody` 的组合使用使得Spring MVC能够轻松地处理RESTful API的请求和响应。它们简化了数据交换的过程,减少了手动序列化和反序列化的代码,提高了开发效率。通过理解这两...

    SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(下)

    在Spring MVC框架中,`@RequestBody` 和 `@ResponseBody` 是两个非常重要的注解,它们在处理HTTP请求和响应时起到了关键作用。本篇文章将详细解释这两个注解的工作原理、使用场景以及如何实现Java对象与XML/JSON数据...

    @ResponseBody 和 @RequestBody 注解的区别

    @ResponseBody 和 @RequestBody 注解的区别 在 Spring 框架中,@ResponseBody 和 @RequestBody 是两个常用的注解,它们都用于处理 HTTP 请求和响应,但是它们的作用和使用场景却有所不同。 一、@ResponseBody 注解...

    Spring MVC打印@RequestBody、@Response日志的方法

    Spring MVC框架提供了强大的日志记录功能,对于日志记录的实现,Spring MVC提供了多种方式,本文将主要介绍如何使用RequestBodyAdvisor和ResponseBodyAdvisor来实现对@RequestBody和@Response的日志输出。...

    springMvc注解之@ResponseBody和@RequestBody详解

    Spring MVC注解之@ResponseBody和@RequestBody详解 在Spring MVC框架中,@ResponseBody和@RequestBody是两个非常重要的注解,它们分别用于处理HTTP请求响应体和请求体的序列化和反序列化。下面,我们将详细介绍这两...

    springMvc注解之 ResponseBody和 RequestBody.docx

    总结来说,`@RequestBody`和`@ResponseBody`是Spring MVC处理JSON数据的两个核心工具。`@RequestBody`用于从请求体中读取JSON数据并映射到方法参数,而`@ResponseBody`则将方法的返回值转换为JSON并发送到客户端。...

    详解使用@RequestBody取POST方式的json字符串

    总结来说,`@RequestBody`是Spring MVC中处理POST请求JSON数据的关键工具。它可以将JSON字符串转换为Java对象,如直接转换为String,或者转换为Map以便处理动态结构的数据。为了确保正确运行,记得在项目中包含必要...

    彻底根治Spring @ResponseBody JavaScript HTML特殊字符

    在开发Web应用时,我们经常会遇到一个问题:当使用Spring MVC的`@ResponseBody`注解将后端处理结果直接转化为HTTP响应体时,如果这个结果中包含HTML特殊字符,如尖角号、引号、按位与符号等,浏览器可能会误解析,...

    快速解决SpringMVC @RequestBody 用map接收请求参数的问题

    在使用 @RequestBody 注解时,我们需要注意的是,它接收的是一个 Json 对象的字符串,而不是一个 Json 对象。例如: ```java @RequestMapping(value = "saveUser", method = {RequestMethod.POST}) @ResponseBody ...

    springmvc实现json交互-requestBody和responseBody

    在Spring MVC中,`@RequestBody`和`@ResponseBody`两个注解是实现JSON交互的关键。`@RequestBody`注解用于读取HTTP请求的内容,通常是请求体中的JSON字符串。Spring MVC通过HttpMessageConverter接口将这个字符串...

    SpringMVC restful 注解之@RequestBody进行json与object转换

    在Spring MVC中,`@RequestBody`注解是用于将HTTP请求体中的数据转换为Java对象的,特别适用于处理JSON或XML格式的数据。当控制器方法接收POST、PUT等带有请求体的HTTP请求时,`@RequestBody`可以帮助我们将接收到的...

    最新版本 jackson 2.8.2 jar与spring 4.x @ResponseBody配合使用

    3. **Spring MVC与@RequestBody和@ResponseBody**: - **@RequestBody**:此注解用于控制器方法的参数,表示请求体中的内容应被转换为该参数的对象。Spring会使用合适的HttpMessageConverter(如Jackson的`...

    spring mvc(整合了json)

    4. **控制器方法的编写**:在 Spring MVC 的控制器类中,我们可以定义处理 HTTP 请求的方法,并使用 `@RequestBody` 和 `@ResponseBody` 注解来接收和返回 JSON 数据。例如: ```java @RequestMapping(value = "/...

    springMVC的 RequestBody和 ResponseBody和RequestParam.docx

    ### Spring MVC 中的 RequestBody 和 ResponseBody 及 RequestParam 使用详解 #### 一、Spring MVC 概述 Spring MVC 是 Spring Framework 的一部分,它提供了一种清晰的模型—视图—控制器架构实现,用于构建 Web ...

    @Response和@Request

    我们将详细探讨`@ResponseBody`和`@RequestBody`。 `@RequestBody`注解用于将HTTP请求正文中的数据转换为Java对象。当控制器方法的参数带有`@RequestBody`时,Spring会查找合适的`HttpMessageConverter`来解析请求...

    Spring MVC – Easy REST-Based JSON Services with @ResponseBody

    标题中的“Spring MVC – Easy REST-Based JSON Services with @ResponseBody”是指使用Spring MVC框架构建基于REST的JSON服务,并通过使用`@ResponseBody`注解来简化这一过程。REST(Representational State ...

    Spring MVC之@RequestMapping详解

    当使用`@RequestBody`和`@ResponseBody`时,Spring会自动寻找合适的Converter进行数据转换。例如,对于JSON数据,Jackson或Gson库的Converter会被使用,将Java对象转换成JSON字符串,反之亦然。 示例代码: ```java...

Global site tag (gtag.js) - Google Analytics