本篇文章写给刚接触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. ios-制作静态.a文件

    一.制作静态库文件 /*静态库制作*/ // MakeA.h -(NSString*)testA; // MakeA.m -(NSString*)testA{ return @"静态库测试成 ...

  2. gRPC helloworld service, RESTful JSON API gateway and swagger UI

    概述 本篇博文完整讲述了如果通过 protocol buffers 定义并启动一个 gRPC 服务,然后在 gRPC 服务上提供一个 RESTful JSON API 的反向代理 gateway,最后 ...

  3. DLoopDetector回环检测算法

    词袋模型是一种文本表征方法,它应用到计算机视觉领域就称之为BoF(bag of features),通过BoF可以把一张图片表示成一个向量.DBoW2是一个视觉词袋库,它提供了生成和使用词典的接口,但 ...

  4. Linux中的info指令

    Info 是什么?info是一种文档格式,也是阅读此格式文档的阅读器:我们常用它来查看Linux命令的info文档.它以主题的形式把几个命令组织在一起,以便于我们阅读:在主题内以node(节点)的形式 ...

  5. CodeForces 747E Comments

    栈,模拟. 手动写一个栈模拟一下过程即可. #include<cstdio> #include<cstring> #include<string> #include ...

  6. [MFC美化] SkinMagic使用详解3- 常见使用问题解答

    在SkinMagic使用过程中,经常遇到以下几个问题: 1. 静态加载皮肤文件时,资源文件IDR_SKIN_CORONA可能会报错:未声明的标识符 解决方法:添加头文件"Resource.h ...

  7. 面向对象UML中类关系

    如果你确定两件对象之间是is-a的关系,那么此时你应该使用继承:比如菱形.圆形和方形都是形状的一种,那么他们都应该从形状类继承而不是聚合.如果你确定两件对象之间是has-a的关系,那么此时你应该使用聚 ...

  8. 在http编程的门口----飞牛网自动下单,查单

    刚进这个公司,以前没接触过http编程,所以这两天做了个小例子来熟悉http编程,有点晕..... 不过还是做出来了,虽然有点粗糙,总结一下这个小软件: 主要使用QNetworkAccessManag ...

  9. PXE+kickstart自动安装ubuntu14.04

    本文参考了诸多文章,先感谢这些文章的作者. 使用pxe安装系统需要安装dhcp,tftp,http等服务(当然也可以使用其他文件共享方式比如nfs,ftp). 实验环境: 1. vmware 12 2 ...

  10. Chapter 2 Open Book——33

    My chin raised a fraction. 我的下巴抬起来了一点. 我略微抬起下颚. "No, she did not send me here. I sent myself.&q ...