SpringMVC札集(07)——JSON数据


自定义View系列教程00–推翻自己和过往,重学自定义View
自定义View系列教程01–常用工具介绍
自定义View系列教程02–onMeasure源码详尽分析
自定义View系列教程03–onLayout源码详尽分析
自定义View系列教程04–Draw源码分析及其实践
自定义View系列教程05–示例分析
自定义View系列教程06–详解View的Touch事件处理
自定义View系列教程07–详解ViewGroup分发Touch事件
自定义View系列教程08–滑动冲突的产生及其处理


探索Android软键盘的疑难杂症
深入探讨Android异步精髓Handler
详解Android主流框架不可或缺的基石
站在源码的肩膀上全解Scroller工作机制


Android多分辨率适配框架(1)— 核心基础
Android多分辨率适配框架(2)— 原理剖析
Android多分辨率适配框架(3)— 使用指南


有时浏览器发送给服务器的请求数据是JSON格式;有时服务器返回给浏览器的数据是JSON格式。那么,SpringMVC是怎么支持JSON格式的呢?在SpringMVC可用@RequestBody和@ResponseBody这两个注解来处理JSON数据。

@RequestBody注解用于读取http请求的内容,通过SpringMVC提供的HttpMessageConverter接口将读到的内容转换为Object并绑定到controller方法的参数上。

@ResponseBody注解用于将Controller的方法返回的对象通过HttpMessageConverter接口转换为指定格式的数据(如:json,xml等)后再通过Response响应给客户端

在本篇博客中,我们举两个例子:
第一个例子:请求数据的格式为JSON,返回数据的格式也为JSON
第二个例子:请求数据的格式为Object,返回数据的格式为JSON

具体实现,请往下看。


第一步:配置springmvc.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


    <!-- 配置自动扫描 -->
    <context:component-scan base-package="cn.com"></context:component-scan>

    <!-- 配置注解开发所需的处理器映射器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>

    <!-- 配置注解开发所需的处理器适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
        <list>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
        </list>
        </property>
    </bean>


    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsps/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


</beans>

请注意,在处理器适配器中配置消息转换器messageConverters


第二步:编写jsp页面

<%@ 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>测试SpringMVC对于JSON数据的处理</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.js">
</script>
<script type="text/javascript">

 //第一个例子:请求数据的格式为JSON,返回数据的格式也为JSON
 function requestJsonData(){
    var userJSON = JSON.stringify({id : "9527",username : "周星星",sex : "男",address : "香港"});
    $.ajax({
        type : 'POST',
        url : '${pageContext.request.contextPath}/json/requestJson.do',
        contentType : 'application/json;charset=utf-8',
        dataType: 'json',
        data : userJSON,
        success : function(data) {
            alert(data.username + "," + data.id + "," + data.sex + "," + data.address);
        }
      })
    }

   //第二个例子:请求数据的格式为Object,返回数据的格式为JSON
   function requestObjectData() {
        $.ajax({
            type : 'POST',
            url : '${pageContext.request.contextPath}/json/requestObject.do',
            contentType :'application/x-www-form-urlencoded;charset=utf-8',
            dataType: 'json',
            data : 'id=9527&username=周星星&sex=男&address=香港',
            success : function(data) {
                alert(data.username + "," + data.id + "," + data.sex + ","+ data.address);
            }
        })
    }
</script>
</head>
<body>
<br>
<input type="button" onclick="requestJsonData()" value="第一个例子:请求数据的格式为JSON,返回数据的格式也为JSON">
<br>
<br>
<input type="button" onclick="requestObjectData()" value="第二个例子:请求数据的格式为Object,返回数据的格式为JSON">
</body>
</html>
  • 在AJAX中利用dataTye表示服务器返回的数据类型
  • 在AJAX中利用contentType表示发送的数据的类型
  • 在AJAX中利用data表示发起请求时携带至服务器的数据
  • 在AJAX中利用success : function(data) {}表示请求的回调,其中data表示服务器返回的数据

在第一个例子中:请求数据的格式为JSON,服务器返回的数据的格式也为JSON。
在第二个例子中:请求数据的格式为Object,服务器返回的数据的格式也为JSON。

运行后效果如下:

这里写图片描述


第三步:实现Controller

/** 
* @author 原创作者:谷哥的小弟
* @blog   博客地址:http://blog.csdn.net/lfdfhl
* @time   创建时间:2017年7月30日 上午8:38:26 
* @info   描述信息:SpringMVC对于JSON数据的处理
*/
package cn.com.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.ResponseBody;
import cn.com.domain.User;

@Controller
@RequestMapping("/json")
public class AnnotationController {

    //第一个例子:请求数据的格式为JSON,返回数据的格式也为JSON
    @RequestMapping("requestJson")
    public @ResponseBody User requestJson(@RequestBody User user){
        System.out.println(user);
        //模拟服务端返回的数据
        User responseUser=user;
        return responseUser;
    }

    //第二个例子:请求数据的格式为Object,返回数据的格式为JSON
    @RequestMapping("requestObject")
    public @ResponseBody User requestObject(User user){
        System.out.println(user);
        //模拟服务端返回的数据
        User responseUser=user;
        return responseUser;
    }
}

在第一个例子中:利用@RequestBody注解将页面传递过来的参数转换为User类对象user;@ResponseBody注解会将方法返回的User类对象responseUser转换为JSON数据返回至浏览器

在第二个例子中:@ResponseBody注解会将方法返回的User类对象responseUser转换为JSON数据返回至浏览器

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷哥的小弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值