1.@RequestBody   (自动将请求的数据封装为对象)

作用:

@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。

传统的请求参数:

itemEdit.action?id=1&name=zhangsan&age=12

现在的请求参数:

使用POST请求,在请求体里面加入json数据

{

"id": 1,

"name": "测试商品",

"price": 99.9,

"detail": "测试商品描述",

"pic": "123456.jpg"

}

2.@ResponseBody

作用:

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

总结:

  在controller中我们可以在方法上面添加@ResponseBody注解,这样我们返回实体对象或者字符串时,就会自动转换成json对象传给前端。在spring4.0后,@ResponseBody又可以加在类上,表示该类中的所有方法都加有@ResponseBody,很方便。另一种方式是使用@RestController注解在类上,作用等于@Controller与@ResponseBody同时加在类上,这也是最方便的一种方式。要让@ResponseBody在类上也起作用,需要在springmvc配置文件中加上<mvc:annotation-driven />这一行配置才可以。而@ResponseBody使用在方法上,则不用添加该配置也可以使用。也就是说springmvc默认只支持@ResponseBody在方法上使用,不支持在类上的使用。

  在实际项目中,我们可能会将后台管理项目与app的后台放在一个项目里面,这样就等于是两个后台共用一套springmvc的配置文件。但是app后台的controller都是返回json信息的,而后台管理是用来返回jsp界面的,会有点混乱。这种情况下,我们需要同时配置<mvc:annotation-driven />和viewResolver,这样的话,app后台的controller都加上@RestController即可,而后台管理的controller则不要@ResponseBody和@RestController,只返回字符串格式的jsp文件名即可。这样就可以两不耽误,两个项目合在一起开发了。

查看RestController的源码:  (是一个组合注解)

/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.web.bind.annotation; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.stereotype.Controller; /**
* A convenience annotation that is itself annotated with {@link Controller @Controller}
* and {@link ResponseBody @ResponseBody}.
* <p>
* Types that carry this annotation are treated as controllers where
* {@link RequestMapping @RequestMapping} methods assume
* {@link ResponseBody @ResponseBody} semantics by default.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController { /**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
* @since 4.0.1
*/
String value() default ""; }

例如:

package cn.xm.jwxt.controller.common;

import cn.xm.jwxt.bean.common.Dictionary;
import cn.xm.jwxt.service.common.DictionaryService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import java.sql.SQLException;
import java.util.List; /**
* 字典controller
*/ @RequestMapping("/dictionary")//基本的映射路径
//@ResponseBody//所有方法返回都是以JSON形式返回
//@Controller//控制层代码
@RestController//这个注解等于@ResponseBody+@Controller
public class DictionaryController {
@Autowired
private DictionaryService dictionaryService;
private Logger logger = Logger.getLogger(DictionaryController.class); @RequestMapping("/getDictionaryTree")
public List<Dictionary> getDictionaryTrees() {
List<Dictionary> dictionaryTree = null;
try {
dictionaryTree = dictionaryService.getDictionaryTree();
} catch (SQLException e) {
logger.error("查询字典树出错!",e);
}
return dictionaryTree;
} }

3.请求json,响应json实现:

3.1. 加入jar包

如果需要springMVC支持json,必须加入json的处理jar

我们使用Jackson这个jar,如下图:

3.1 JSP页面ajax请求

<script type="text/javascript">

$(function(){
var param='{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';
$.ajax({
url:"${pageContext.request.contextPath }/json.action",
async:true,
type:"POST",
data:param,
contentType : "application/json;charset=UTF-8",//发送数据的格式
success: function(data){
alert(data.name);
},
error:function(){
alert("请求失败");
},
dataType:"json" //回掉数据格式
}); })
</script>

3.2.处理ajax请求的controller

@RequestMapping(value = "/json.action")
public @ResponseBody Items json(@RequestBody Items items){
// 设置@RequestBody后子发动将ajax请求封装为对象
System.out.println(items); // 设置@ResponseBody后自动将返回的数据封装为ajax
return items;
}

3.3 配置json转换器

如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器,参考之前学习的自定义参数绑定。

在springmvc.xml配置文件中,给处理器适配器加入json转换器:

<!--处理器适配器 -->

   <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>

SpringMVC的JSON数据交互(七)-@Response,@RestController,@RequestBody用法的更多相关文章

  1. springmvc的json数据交互

    准备 @RequestBody 作用: @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json ...

  2. SpringMVC与Json数据交互

    简单回顾了一下SpringMVC和前端JSON数据是怎么交互的 接下来详细说一下过程 前端代码写的很简单  主要是为了试验一下JSON数据的前后台传递 前端代码给大家发出来 其实真的很简单 前端接受了 ...

  3. SpringMVC之json数据交互

    在Spring3.1之后,如果使用<mvc:annotation-driven />,即使用注解驱动,默认情况下已经配置了MappingJackson2HttpMessageConvert ...

  4. SpringMVC进行json数据交互

    请求key/value.输出json.此方法在开发中比较常用. 在注解适配器中加入messageConverters <!--注解适配器 --> <bean class=" ...

  5. json数据交互

    springmvc 的json数据交互 - 哎幽的成长 - CSDN博客--和老师讲课相同http://blog.csdn.net/u012373815/article/details/4720818 ...

  6. springmvc-高级参数绑定-映射-异常-json数据交互-拦截器

    1.1. 高级参数绑定 1.1.1. 复制工程 把昨天的springmvc-web工程复制一份,作为今天开发的工程 复制工程,如下图: 粘贴并修改工程名为web2,如下图: 工程右键点击,如下图: 修 ...

  7. SpringMVC JSON数据交互

    本节内容: @RequestBody @ResponseBody 请求json,响应json实现 前端可以有很多语言来写,但是基本上后台都是java开发的,除了c++(开发周期长),PHP和#Net( ...

  8. SpringMVC入门(二)—— 参数的传递、Controller方法返回值、json数据交互、异常处理、图片上传、拦截器

    一.参数的传递 1.简单的参数传递 /* @RequestParam用法:入参名字与方法名参数名不一致时使用{ * value:传入的参数名,required:是否必填,defaultValue:默认 ...

  9. SprimgMVC学习笔记(八)—— SpringMVC与前台json数据交互

    一.两种交互形式 可以看出,前台传过来的方式有两种,一种是传json格式的数据过来,另一种就是在url的末尾传普通的key/value串过来,针对这两种方式,在Controller类中会有不同的解析, ...

随机推荐

  1. 【Linux】Centos配置ssh无密码登录

    [测试环境] 刚好重新做mgr就搞下吧,主要论文好长~想多做几遍再看~ master1 192.168.13.111 master2 192.168.13.112  master3  192.168. ...

  2. BZOJ5294 [BJOI2018] 二进制 【线段树】

    BJOI的题目感觉有点难写 题目分析: 首先推一波结论.接下来的一切都在模3意义下 现在我们将二进制位重组,不难发现的是2^0≡1,2^1≡2,2^2≡1,2^3≡2....所以我们考虑这样的式子 2 ...

  3. android studio+grade配置构建

    Android 构建系统编译应用资源和源代码,然后将它们打包成可供您测试.部署.签署和分发的 APK.android Studio 使用 Gradle 这一高级构建工具包来自动化执行和管理构建流程,同 ...

  4. Android recording 录音功能 简单使用小实例

    package com.app.recordingtest; import java.io.File; import java.io.IOException; import android.app.A ...

  5. [luogu1447][bzoj2005][NOI2010]能量采集

    题目大意 求出\(\sum_{i=1}^{n} \sum_{i=1}^{m} gcd(i,j)\times 2 -1\). 题解 解法还是非常的巧妙的,我们考虑容斥原理.我们定义\(f[i]\)表示\ ...

  6. linux-shell数据重定向详细分析

    在了解重定向之前,我们先来看看linux 的文件描述符.linux文件描述符:可以理解为linux跟踪打开文件,而分配的一个数字,这个数字有点类似c语言操作文件时候的句柄,通过句柄就可以实现文件的读写 ...

  7. Elasticsearch 基础知识要点与性能监控

    本文的来源是我翻译国外的一篇技术博客,感谢原作者Emily Chang,原文地址通过如下的知识,我们能大致学到关于ES的一些基本知识,进而对elasticsearch的性能进行监控和调优 注意elas ...

  8. SDL2.0 VLC ubuntu安装和黑屏问题

    开发环境安装: 1,执行:"sudo apt-get build-dep libsdl1.2",确定依赖库都装全了. sdl2.0没有正式发布到ubuntu,使用下面方法安装: h ...

  9. Centos6.5之ssh免密码登录配置

    Centos6.5之ssh免密码登录配置 centos ssh 免密码登录 0.说明 这里为了方便说明问题,假设有A和B两台安装了centos6.5的主机.目标是实现A.B两台主机分别能够通过ssh免 ...

  10. 省选前的CF题

    RT,即将退役的人懒得一篇篇写题解,于是有了这个东西 CF1004E 树上选一条不超过k个点的链,最小化其余点到链上点的最大距离 这个思路很有意思,不像平时一般的树上问题,是从叶子开始一点点贪心合并直 ...