当前位置: 代码迷 >> JavaScript >> springMVC_04 Ajax请求 @RequestBody,@ResponseBody 处置JSON格式
  详细解决方案

springMVC_04 Ajax请求 @RequestBody,@ResponseBody 处置JSON格式

热度:4168   发布时间:2014-03-01 00:37:32.0
springMVC_04 Ajax请求 @RequestBody,@ResponseBody 处理JSON格式

springMVC处理Ajax请求,返回JSON格式数据

加入对jackson的依赖,springMVC使用jackson进行JSON数据转换

		<!-- json -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.10</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.10</version>
		</dependency>

?

Controller

package com.gc.springmvc.controller;

import java.util.ArrayList;
import java.util.List;

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

import com.gc.springmvc.model.User;

@Controller
public class AjaxController {
	
	@RequestMapping(value="listUser")
	public @ResponseBody List<User> listUser() throws Exception {
		List<User> users = new ArrayList<User>();
		users.add(new User("张三2", "zs"));
		users.add(new User("李四", "ls"));
		return users;
	}
	
}

?

页面

<%@ 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>Insert title here</title>
</head>
<body>
	<div>
		<div>
			<a href="javascript:void(0)" onclick="sendAjaxReq()">Ajax请求,返回JSON数据</a>
		</div>
		<div id="users" style="margin-left:50%;font-weight:bold;color:red"></div>
	</div>
	
	<!-- Ajax -->
	<script type="text/javascript">
		function createAjaxObj() {
			var req;
			if (window.XMLHttpRequest) {
				req = new XMLHttpRequest();
			} else {
				req = new ActiveXObject("Msxml2.XMLHTTP"); //ie
			}
			return req;
		}

		function sendAjaxReq() {
			var req = createAjaxObj();
			req.open("get", "listUser?name=王五&time="+Math.random());
			req.setRequestHeader("accept", "application/json");
			req.onreadystatechange = function() {
				if(req.readyState=4 && req.status==200) {
					var result = eval("(" + req.responseText +")");
					var divNode = document.getElementById("users");
					divNode.innerHTML = "";
					for(var index in result) {
						var name = result[index].name;
						if(index>0) {
							name = "<br/>" + name;
						}
						divNode.innerHTML += name;
					}
				}
			}
			req.send(null);
		}
	</script>
</body>
</html>

?

?

JSP页面中访问服务器上的静态资源,如js脚本文件

必须配置resource资源,否则按请求一个Controller进行映射处理,导致无法下载

?

    <!-- 配置对静态资源文件的访问不被拦截,如js脚本-->
    <mvc:resources location="/script/" mapping="/script/**"/>
?

?

配置文件中只需要加入如下配置,即可开启一系列功能:
<mvc:annotation-driven/>
如果类路径下有jackson相关jar包,springMVC将自动注册JSON转换服务!
HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values from @RequestMapping or @ExceptionHandler methods.
??? This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:
??????? ByteArrayHttpMessageConverter converts byte arrays.
??????? StringHttpMessageConverter converts strings.
??????? ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.
??????? SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.
??????? FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.
??????? Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present on the classpath.
??????? MappingJackson2HttpMessageConverter (or MappingJacksonHttpMessageConverter) converts to/from JSON — added if Jackson 2 (or Jackson) is present on the classpath.
??????? AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.
??????? RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.

?

?

@RequestBody

?????? 客户端将JSON数据发送到服务端,服务端将JSON转换为对象传入
??????
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
    // implementation omitted
}
?

?

@ResponseBody

服务端将对象转为JSON传递到浏览器,因此,多用于get方式请求JSON数据

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
    // implementation omitted
}

?

?

示例:

客户端发起Ajax请求,Post方式,将JSON数据发送到服务端

服务端通过@RequestBody将JSON数据转换为对象

服务端再通过@ResponseBody将对象转换为JSON数据返回给客户端

?

Controller控制器

package com.gc.springmvc.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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gc.springmvc.model.User;

@Controller
public class AjaxController {
	
	/**
	 * 接收客户端发送的JSON数据,并将其转换为对象
	 * @RequestBody 
	 * 其一,从http请求报文的请求体中获取JSON数据,则说明必须是POST请求
	 * 其二,Body中为JSON,则最可能为Ajax请求,通过form进行post请求好像办不到呢
	 */
	@RequestMapping(value="jsonPost", method=RequestMethod.POST, consumes="application/json")
	@ResponseBody
	public User jsonPost(@RequestBody User user) {
		System.out.println("ajax json post");
		System.out.println(user.getName());
		System.out.println(user.getPassword());
		user.setName("李四");
		user.setPassword("100");
		return user;
	}
}

?

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>Insert title here</title>
</head>
<body>
	<div>
		<fieldset>
			<table>
				<tbody>
					<tr>
						<td>name</td>
						<td><input id="name" type=text value="张三"/></td>
					</tr>
					<tr>
						<td>password</td>
						<td><input id="password" type=password value="123"/></td>
					</tr>
					<tr>
						<td><button id="post">ajax:POST</button></td>
					</tr>
				</tbody>			
			</table>
		</fieldset>
	</div>
	<script type="text/javascript" src="script/jquery-1.9.1.js"></script>
	<script type="text/javascript">
		$(document).ready(function(){
			$("#post").click(function(){
				ajaxPOST();
			});
		});
		
		function ajaxPOST() {
			var user = {};
			user.name = $("#name").val();
			user.password = $("#password").val();
			var jsonStr = JSON.stringify(user);
			//var json2Object = JSON.parse(jsonStr);
			$.ajax({
				type : "post",
				contentType : "application/json;charset=UTF-8",
				url : "jsonPost",
				dataType : "json",
				processData : false,
				data : jsonStr,
				success : function(msg) {
					//javascript已自动将返回的json数据转为对象了
					alert("success:"+msg.name+"---"+msg.password);
				},
				error : function() {
					alert("try again!");
				}
			});
		}
		
	</script>
</body>
</html>

?

?

?

?

?

?

?

?

?

  相关解决方案