一、json数据交互:

json数据格式在接口调用中、html页面中较常用,json格式比较简单,解析还比较方便。

比如:webservice接口,传输json数据.

springMVC进行json交互

1)环境准备:

加载json转换的jar包:

springmvc中使用jackson的包进行json转换(@requestBody和@responseBody使用下边的包进行json转)

jackson-core-asl-1.9.11.jar

jackson-mapper-asl-1.9.11.jar

2)配置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>

如果使用<mvc:annotation-driven /> 则不用定义上边的内容。

3)代码实现:测试:

 package com.cy.controller;

 import org.springframework.beans.factory.annotation.Autowired;
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 com.cy.po.ItemsCustom;
import com.cy.service.ItemsService; /**
* json交互测试
*
*/
@Controller
public class JsonTest { @Autowired
private ItemsService itemsService; //请求json串(商品信息),输出json(商品信息)
//@RequestBody将请求的商品信息的json串转成itemsCustom对象
@RequestMapping("/requestJson")
@ResponseBody
public ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom) throws Exception{
int id = itemsCustom.getId();
ItemsCustom itemsCustom2 = itemsService.findItemsById(id);
return itemsCustom2;
} //请求key/value,输出json
//@ResponseBody将itemsCustom转成json输出
@RequestMapping("/responseJson")
@ResponseBody
public ItemsCustom responseJson(ItemsCustom itemsCustom) throws Exception{
int id = itemsCustom.getId();
ItemsCustom itemsCustom2 = itemsService.findItemsById(id);
return itemsCustom2;
}
}

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>json交互测试</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
//请求json,输出是json
function requestJson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/requestJson.action',
contentType:'application/json;charset=utf-8',
//数据格式是json串,商品信息
//这边很严格的做了测试,必须是这种格式;
//key加引号;整个{}加引号;整个就是一个json串;有点像JOSN.stringify(JOSNObject)这样子
data:'{"id":1,"name":"手机","price":999}',
success:function(data){
console.log(data);
} });
}
//请求key/value,输出是json
function responseJson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/responseJson.action',
data:'id=4&name=手机&price=999',
success:function(data){//返回json结果
console.log(data);
}
});
}
</script>
</head>
<body>
<input type="button" onclick="requestJson()" value="请求json,输出是json"/>
<input type="button" onclick="responseJson()" value="请求key/value,输出是json"/>
</body>
</html>

测试结果:

数据库内容:

requestJson:

responseJson:

二、RESTful支持:

RESTful介绍:

RESTful(即Representational State Transfer的缩写)其实是一个开发理念,是对http的很好的诠释。

1、对url进行规范,写RESTful格式的url

非REST的url:http://...../queryItems.action?id=001&type=T01

REST的url风格:http://..../items/001

特点:url简洁,将参数通过url传到服务端

2、http的方法规范

不管是删除、添加、更新。。使用url是一致的,如果进行删除,需要设置http的方法为delete,同理添加put。。。

后台controller方法:判断http方法,如果是delete执行删除,如果是post执行更新。

3、对http的contentType规范

请求时指定contentType,要json数据,设置成json格式的type。。

下面是RESTful的例子:这个例子主要是对url进行了规范:

1)ItemsController:

定义方法,进行url映射使用REST风格的url,将查询商品信息的id传入controller .

@Controller
@RequestMapping("/items")
public class ItemsController { @Autowired
private ItemsService itemsService; //查询商品信息,输出json
///itemsView/{id}里边的{id}表示占位符,通过@PathVariable获取占位符中的参数,
//如果占位符中的名称和形参名一致,在@PathVariable可以不指定名称
@RequestMapping("/itemsView/{id}")
@ResponseBody
public ItemsCustom itemsView(@PathVariable("id") Integer itemId)throws Exception{
ItemsCustom itemsCustom = itemsService.findItemsById(itemId);
return itemsCustom;
} ....
}

2)REST风格的前端控制器配置、静态资源文件配置:

由于REST风格是url是不带后缀的,这里配置url-pattern为/,亦需要配置静态文件不让dispatcherServlert解析:

web.xml中配置:

 <!-- springmvc前端控制器,rest配置 -->
<servlet>
<servlet-name>springmvc_rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc_rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

springmvc中配置访问静态资源:

<mvc:resources  mapping="/resources/**"  location="/resources/" />
<mvc:resources mapping="/js/**" location="/js/"/>

访问结果:

springMVC学习(11)-json数据交互和RESTful支持的更多相关文章

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

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

  2. Spring MVC之JSON数据交互和RESTful的支持

    1.JSON概述 1.1 什么是JSON JSON(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式.它是基于JavaScript的一个子集,使用了C.C ...

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

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

  4. SpringBoot学习之Json数据交互

    最近在弄监控主机项目,对javaweb又再努力学习.实际的项目场景中,前后分离几乎是所以项目的标配,全栈的时代的逐渐远去,后端负责业务逻辑处理,前端负责数据展示成了一种固定的开发模式.像thymele ...

  5. springmvc学习笔记(18)-json数据交互

    springmvc学习笔记(18)-json数据交互 标签: springmvc springmvc学习笔记18-json数据交互 springmvc进行json交互 环境准备 加入json转换的依赖 ...

  6. spring-boot json数据交互

    SpringBoot学习之Json数据交互 最近在弄监控主机项目,对javaweb又再努力学习.实际的项目场景中,前后分离几乎是所以项目的标配,全栈的时代的逐渐远去,后端负责业务逻辑处理,前端负责数据 ...

  7. 【SpringMVC学习09】SpringMVC与前台的json数据交互

    json数据格式在接口调用中.html页面中比较常用,json格式比较简单,解析也比较方便,所以使用很普遍.在springmvc中,也支持对json数据的解析和转换,这篇文章主要总结一下springm ...

  8. (转)SpringMVC学习(十)——SpringMVC与前台的json数据交互

    http://blog.csdn.net/yerenyuan_pku/article/details/72514022 json数据格式在接口调用中.html页面中比较常用,json格式比较简单,解析 ...

  9. SpringMVC JSON数据交互

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

随机推荐

  1. 量身打造自己的MyEclipse(多图)

    迎新年 贺元旦MyEclipse推新版 在线订购低至 7.5 折!截止1月31号(活动期间在线下单的客户才可享受此优惠,过期恢复原价) 立即抢购 1.量身打造你自己的MyEclipse MyEclip ...

  2. 离线使用Visual Studio的Javascript Prettier插件

    用Prettier插件来格式化Javascript代码效果好的不得了,简直是强迫症的救命克星,可惜单位的电脑是不联网的,始终用不了,今天抽空研究了一下,找到办法了. 1.下载JavaScript Pr ...

  3. UITableViewCell的高度与UILabel自适应

    UITableViewCell内部只放了一个UILabel,Cell的高度随着UILabel内容的高度变化而变化,可重写UITableView的委托方法动态调整高度,还要设置UILabel.numbe ...

  4. Java乱码解决之道

    1.常见字符编码 ASCII编码: ASCII,American Standard Code for Information Interchange,是基于拉丁字母的一套电脑编码系统,主要用于显示现代 ...

  5. Codeforces 698A:Vacations(DP)

    题目链接:http://codeforces.com/problemset/problem/698/A 题意 Vasya在n天中,有三件事情可以做,健身.比赛或者休息,但是不能连续两天都是比赛或都是但 ...

  6. List<Map<String, Integer>> 同key的value全部累加合并

    public static void main(String[] args){ List<Map<String,Object>> list1 = new ArrayList&l ...

  7. 【BZOJ3110】【Zjoi2013】K大数查询 - 2

    之前用权值线段树套区间线段树水过,现在再练习一下整体二分 原题:有N个位置,M个操作.操作有两种,每次操作如果是1 a b c的形式表示在第a个位置到第b个位置,每个位置加入一个数c如果是2 a b ...

  8. 【BZOJ1703】【usaco2007margold】ranking the cows 奶牛的魅力排名

    想的时间比较长所以看题解了= = 原题: Fj有N(N<=1000)头牛,每头牛都有独一无二的正整数 魅力值,Fj想让他们按 魅力值排序. Fj已经知道M(1<=M<=10000)对 ...

  9. LG2023 [AHOI2009]维护序列

    题意 老师交给小可可一个维护数列的任务,现在小可可希望你来帮他完成. 有长为N的数列,不妨设为a1,a2,-,aN .有如下三种操作形式: (1)把数列中的一段数全部乘一个值; (2)把数列中的一段数 ...

  10. (精)AVL树旋转共8种情况(涵盖所有考研的范围)