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/**"/>
 

相关推荐