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

一、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转换器;

如果是配置单个的注解适配器,要加入下面配置:

1 <!--注解适配器 -->
2     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
3         <property name="messageConverters">
4         <list>
5         <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
6         </list>
7         </property>
8     </bean>
View Code

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

3)代码实现:测试:

 1 package com.cy.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestBody;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.ResponseBody;
 8 
 9 import com.cy.po.ItemsCustom;
10 import com.cy.service.ItemsService;
11 
12 /**
13  * json交互测试
14  *
15  */
16 @Controller
17 public class JsonTest {
18     
19     @Autowired
20     private ItemsService itemsService;
21     
22     //请求json串(商品信息),输出json(商品信息)
23     //@RequestBody将请求的商品信息的json串转成itemsCustom对象
24     @RequestMapping("/requestJson")
25     @ResponseBody
26     public  ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom) throws Exception{
27         int id = itemsCustom.getId();
28         ItemsCustom itemsCustom2 = itemsService.findItemsById(id);
29         return itemsCustom2;
30     }
31     
32     //请求key/value,输出json
33     //@ResponseBody将itemsCustom转成json输出
34     @RequestMapping("/responseJson")
35     @ResponseBody
36     public ItemsCustom responseJson(ItemsCustom itemsCustom) throws Exception{
37         int id = itemsCustom.getId();
38         ItemsCustom itemsCustom2 = itemsService.findItemsById(id);
39         return itemsCustom2;
40     }
41 }

jsp页面:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>json交互测试</title>
 8 <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
 9 <script type="text/javascript">
10 //请求json,输出是json
11 function requestJson(){
12     $.ajax({
13         type:'post',
14         url:'${pageContext.request.contextPath }/requestJson.action',
15         contentType:'application/json;charset=utf-8',
16         //数据格式是json串,商品信息
17         //这边很严格的做了测试,必须是这种格式;
18         //key加引号;整个{}加引号;整个就是一个json串;有点像JOSN.stringify(JOSNObject)这样子
19         data:'{"id":1,"name":"手机","price":999}',
20         success:function(data){
21             console.log(data);
22         }
23         
24     });
25 }
26 //请求key/value,输出是json
27 function responseJson(){
28     $.ajax({
29         type:'post',
30         url:'${pageContext.request.contextPath }/responseJson.action',
31         data:'id=4&name=手机&price=999',
32         success:function(data){//返回json结果
33             console.log(data);
34         }
35     });
36 }
37 </script>
38 </head>
39 <body>
40 <input type="button" onclick="requestJson()" value="请求json,输出是json"/>
41 <input type="button" onclick="responseJson()" value="请求key/value,输出是json"/>
42 </body>
43 </html>
View Code

测试结果:

数据库内容:

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中配置:

 1 <!-- springmvc前端控制器,rest配置 -->
 2     <servlet>
 3         <servlet-name>springmvc_rest</servlet-name>
 4         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 5         <init-param>
 6             <param-name>contextConfigLocation</param-name>
 7             <param-value>classpath:spring/springmvc.xml</param-value>
 8         </init-param>
 9     </servlet>
10     <servlet-mapping>
11         <servlet-name>springmvc_rest</servlet-name>
12         <url-pattern>/</url-pattern>
13     </servlet-mapping>
View Code

springmvc中配置访问静态资源:

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

访问结果:

 

posted on 2017-01-21 20:38  有点懒惰的大青年  阅读(632)  评论(0编辑  收藏  举报