作者: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. 其他
淘宝: