本篇文章写给刚接触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. Android call setting 源码分析

    看下篇之前,请先读这三篇文章: Android GSM驱动模块(rild)详细分析(一)基本架构及初始化 Android GSM驱动模块(rild)详细分析(二)request流程 Android G ...

  2. 利用jquery对ajax操作,详解原理(附代码)

    1. jQuery load() 方法 jQuery load() 方法是简单但强大的 AJAX 方法. load() 方法从服务器加载数据,并把返回的数据放入被选元素中. 语法: $(selecto ...

  3. Mybatis-Spring SqlSessionTemplate 源码解析

    在使用Mybatis与Spring集成的时候我们用到了SqlSessionTemplate 这个类. <bean id="sqlSession" class="or ...

  4. react入门——慕课网笔记

    一. jsx 1. 被称为语法糖:糖衣语法,计算机语言中添加的某种语法,对语言的功能没有影响,更方便程序员使用,增加程序的可读性,降低出错的可能性 类似的还有(coffeescript,typescr ...

  5. 2017 年不可错过的开发工具 Top 50

    想知道 2017 年有哪些值得关注的开发工具吗?StackShare 年度开发工具排行榜来啦! StackShare.io 是一个开发者工具及服务分享平台,致力于发现并分享开发者使用的开发工具.服务与 ...

  6. bzoj1588: [HNOI2002]营业额统计 splay瞎写

    最近各种瞎写数论题,感觉需要回顾一下数据结构 写一发splay冷静一下(手速过慢,以后要多练练) 用splay是最直接的方法,但我感觉离散一波应该可以做出来(没仔细想过) 现在没有很追求代码优美,感觉 ...

  7. oracle 增加表空间

    1.表空间使用情况 SELECT UPPER(F.TABLESPACE_NAME) "表空间名", D.TOT_GROOTTE_MB "表空间大小(M)", D ...

  8. 深入分析:微信小程序与H5的区别

    作为前端工程师,从前端的视角,为大家分析下微信小程序和HTML5与之间的主要区别 第一条是运行环境的不同. 传统的HTML5的运行环境是浏览器,包括webview,而微信小程序的运行环境并非完整的浏览 ...

  9. HOOK(钩子)函数

    安装.卸载钩子的相关函数 钩子类型 按功能分: 1.WH_CALLWNDPROC和WH_CALLWNDPROCRET:使你可以监视发送到窗口过程的消息3.WH_DEBUG    调试钩子4.WH_FO ...

  10. 安装 zabbix 时遇到的一个问题

    安装 zabbix 2.0.3,到最后阶段,遇到一个问题: PHP bcmath extension missing,  php configuration parameter --enable-bc ...