springMVC学习(11)-json数据交互和RESTful支持

时间:2021-12-22 16:11:14

一、json数据交互:

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

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

springMVC进行json交互

springMVC学习(11)-json数据交互和RESTful支持

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>

测试结果:

数据库内容:

springMVC学习(11)-json数据交互和RESTful支持

requestJson:

springMVC学习(11)-json数据交互和RESTful支持

responseJson:

springMVC学习(11)-json数据交互和RESTful支持

二、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支持