作者:ssslinppp
1. 摘要
程序流程:
- 前台使用ajax技術,傳遞json字符串到后台;
- 后台使用Spring MVC注解@RequestBody 接受前台傳遞的json字符串,並返回新的json字符串到前台;
- 前台接受后台傳遞過來的json數據,並顯示。

2. 前台界面和js

<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>SpringMVC+ajax+json</title>
<script type="text/javascript">var basePath = "<%=basePath%>";</script>
<%-- <link rel="stylesheet" type="text/css" href="<%=basePath%>js/easyui/demo.css"> --%>
<script type="text/javascript" src="<%=basePath%>js/JQuery/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>js/test/ajaxAndJson.js"></script>
</head>
<body>
<div style="padding:5px 0;">
<p>SpringMVC @RequestBody 接收Json數組對象</p>
<a href="#" class="easyui-linkbutton" onclick="loadData()" data-options="iconCls:'icon-add'">@RequestBody 接收Json數組對象</a>
</div>
</body>
</html>

3. 后台java代碼

http://localhost:8080/SpringMVCTest/test/index.action 請求后,返回index.jsp界面,如下圖:

點擊后會請求jsonDataReq

這是person.java類

4. 配置
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">
<!-- 從類路徑下加載Spring配置文件,classpath關鍵字特指從類路徑下加載 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 負責啟動Spring容器的監聽器 -->
<listener><listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class></listener>
<!-- 配置Spring MVC,其對應的配置文件為:servlet-name-servlet.xml, 本項目的為:spring-servlet.xml -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml

applicationContext.xml

5. 結果


6. 其他
淘寶: