本篇文章写给刚接触SpingMVC的同道中人,虽然笔者本身水平也不高,但聊胜于无吧,希望可以给某些人带来帮助

笔者同时再次说明,运行本例时,需注意一些配置文件和网页脚本的路径,因为笔者的文件路径与读者的未必相同

首先准备以下 jar包:
commons-logging-1.1.3.jar
jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
spring-aop-4.0.6.RELEASE.jar
spring-beans-4.0.6.RELEASE.jar
spring-context-4.0.6.RELEASE.jar
spring-core-4.0.6.RELEASE.jar
spring-expression-4.0.6.RELEASE.jar
spring-web-4.0.6.RELEASE.jar
spring-webmvc-4.0.6.RELEASE.jar
其中commons-logging-1.1.3.jar,jackson-core-asl-1.9.2.jar,jackson-mapper-asl-1.9.2.jar均可在struts2的工具包中取得

导入以上包后,去web.xml中进行配置,配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<display-name>web</display-name> <!-- 配置springMVC请求分配Servlet -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
<!-- 声明配置文件存放位置和配置文件的名称,加入不配置此标签,springMVC的配置文件名称默认为<servlet-name>的值加上"-servlet.xml",例如本例便是springMVC-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/*-servlet.xml</param-value>
</init-param>
-->
<!-- 值小于1时,表示容器启动时并不加载此servlet,此时只有当第一次使用servlet时才会加载,但当值大于等于1时,表示容器启动时会立即加载此servlet,此时值越大表示加载的优先级越小 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!-- 请求链接以do结尾,具体怎么回事请耐心继续往下看 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

接下来我们再看springMVC-servlet.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描指定包下的所有类,倘若发现@Component,@Controller,@Service,@Repsitory等注解,则将相应的类实例化 -->
<context:component-scan base-package="org.xt.controller"/>
<!-- 配置视图资源 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 此乃视图资源的前缀 -->
<property name="prefix" value="/WEB-INF/page"/>
<!-- 此乃视图资源的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 此处乃进行json数据传输的关键,当配置 -->
<bean id="jsonMapping" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMapping"/>
</list>
</property>
</bean>
</beans>

接下来我们再看vo对象即值对象User.java,如下:

package org.xt.pojo;

import java.io.Serializable;

@SuppressWarnings("serial")
public class User implements Serializable {
private long userId;
private String userName;
private String userPassword; public long getUserId() {
return this.userId;
} public void setUserId(long userId) {
this.userId = userId;
} public String getUserName() {
return this.userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getUserPassword() {
return this.userPassword;
} public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}

好接下来便轮到了Controller的类TestJSONController.java,如下:

package org.xt.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 org.xt.pojo.User; @Controller
@RequestMapping("/test")
public class TestJSONController {
/*
*看value属性,是以do结尾的,这正是web.xml配置url-pattern的值为*.do的原因,
*这样所有的请求链接都必须以.do结尾,这样做的好处在于可以将请求链接同其他链接区分开来.
*笔者建议如此做(当然了,你也可以将.do换成.html,.htm或者其他)
*/
@RequestMapping(value = "/testJSON.do",method={RequestMethod.POST})
@ResponseBody
public User testJSON(@RequestBody User user) {
System.out.println(user.getUserName() + " " + user.getUserPassword());
return user;
}
}

在以上类中出现的@ResponseBody和@RequestBody是关键,前者用于将JSON数据返回客户端,后者用于接受客户端的JSON数据

接下来我们来看看客户端的代码,客户端的代码由jquery完成

<%@ 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>TestJSONForSpringMVC</title>
</head>
<body>
用户名:
<input id="userName" type="text" style="width:150px" />
<br />
<br />
密&nbsp;&nbsp;&nbsp;&nbsp;码:
<input id="userPassword" type="password" style="width:150px" />
<br />
<br />
<input id="login" type="button" value="登录" />
<!-- 注意了,此处jquery的路径记得替换成你自己jquery所在的路径 -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#login").click(function() {
$.ajax({
url : "test/testJSON.do",
type : "POST",
dataType : "json",
contentType : "application/json;charset=UTF-8",
data : JSON.stringify({
userId : "1",
userName : $("#userName").val(),
userPassword : $("#userPassword").val()
}),
success : function(result) {
alert(JSON.stringify(result));
},
error:function(result){
alert("Sorry,you are make a error!");
}
});
});
</script>
</body>
</html>

以上jsp文件中出现了一个JSON.stringify()函数,此函数由jquery提供,作用在于将JSON数据转换为字符串,之所以要这么做,原因在于服务端的@RequestBody只能识别字符串,而不能识别JSON对象

--写于2014-09-10 夜

Spring MVC如何进行JSON数据的传输与接受的更多相关文章

  1. Spring mvc,jQuery和JSON数据交互

    一.实验环境的搭建 1.Spring mvc jar. 导入spring mvc运行所需jar包.导入如下(有多余) 2.json的支持jar 3.加入jQuery. 选用jquery-3.0.0.m ...

  2. Spring MVC中返回JSON数据的几种方式

    我们都知道Spring MVC 的Controller方法中默认可以返回ModeAndView 和String 类型,返回的这两种类型数据是被DispatcherServlet拿来给到视图解析器进行继 ...

  3. 1.4(Spring MVC学习笔记)JSON数据交互与RESTful支持

    一.JSON数据交互 1.1JSON简介 JSON(JavaScript Object Notation)是一种数据交换格式. 1.2JSON对象结构 {}代表一个对象,{}中写入数据信息,通常为ke ...

  4. spring MVC之返回JSON数据(Spring3.0 MVC)

    方式一:使用ModelAndView的contentType是"application/json" 方式二:返回String的            contentType是&qu ...

  5. Spring MVC中传递json数据时显示415错误解决方法

    在ajax中设置 ContentType为'application/json;charset=utf-8' 传递的data类型必须是json字符串类型:{“key”:"value" ...

  6. IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践

    原文:IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践 最近把编辑器换成IntelliJ IDEA,主要是Ecli ...

  7. Spring使用fastjson处理json数据

    1.搭建SpringMVC+spring环境 2.配置web.xml以及springmvc-config.xml,web.xml同Spring使用jackson处理json数据一样,Springmvc ...

  8. IntelliJIDEA Getting+Started+with+Spring+MVC,+Hibernate+and+JSON

    https://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC,+Hibernate+and ...

  9. Spring MVC 返回 xml json pdf 数据的配置方法

    <!-- Spring MVC 返回 xml 数据的配置方法 -->     <bean class="org.springframework.web.servlet.vi ...

随机推荐

  1. 64win7+64Oracle+32plsql

    1)安装Oracle 11g 64位   2)安装32位的Oracle客户端( instantclient-basic-win32-11.2.0.1.0) 下载instantclient-basic- ...

  2. CKPlayer 只调用HTML5播放器时全屏问题 这只是Chrome浏览器的渲染bug

    如题,在系统中使用CKPlayer播放器,一切顺利,偶然发现没有全屏按钮, 正常的全屏按钮是这样的: 经过一步步调试,发现问题出在iframe, 当视频页面在iframe内时,全屏按钮不显示了,这个和 ...

  3. Docker集群实验环境布署--swarm【1 架构说明】

    在读完<Docker技术入门与实践>这本书后,基本上已对Docker了有一些入门的理解,以及我们为什么要使用Docker 答:我们发现在实际工作中,通过openstack一旦把一个VM创建 ...

  4. Python 根据地址获取经纬度

    方法一: 使用Geopy包 : https://github.com/geopy/geopy   (仅能精确到城镇,具体街道无结果返回) from geopy.geocoders import Nom ...

  5. js分页模板

    /** *参数说明: *currentPage:当前页数 *countPage:总页数 *changeMethod:执行java后台代码的js函数,即是改变分页数据的js函数 */ function  ...

  6. JS函数调用

        function SayHello(word) { console.log(word); }   function execute(Somefunction,value) { Somefunc ...

  7. 微信js-sdk调用

    之前在做微信的时候,在微信支付还有调起微信扫一扫的时候,用过js-sdk.最近,被几个做前端的同学问到了具体的流程,想想,还是写下来好点.     微信js-sdk,是微信提供给网页开发设计者使用的, ...

  8. [MFC美化] Skin++使用详解-使用方法及注意事项

    主要分为以下几个方面: 1.Skin++使用方法 2.使用中注意事项 一. Skin++使用方法 SkinPPWTL.dll.SkinPPWTL.lib.SkinPPWTL.h ,将三个文件及相应皮肤 ...

  9. CODE[VS]-蛇形矩阵-模拟-天梯白银

    题目描述 Description 小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字,请输出该 ...

  10. 冰刃IceSword中文版 V1.22 绿色汉化修正版

    软件名称: 冰刃IceSword中文版 V1.22 绿色汉化修正版 软件语言: 简体中文 授权方式: 免费软件 运行环境: Win 32位/64位 软件大小: 2.1MB 图片预览: 软件简介: Ic ...