博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring REST
阅读量:6589 次
发布时间:2019-06-24

本文共 7110 字,大约阅读时间需要 23 分钟。

示例实现

1. 请求REST接口返回类转换的JSON或XML数据

2. POST JSON数据到REST接口自动转为类数据

服务端

Bean

package com.qunar.bean;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlRootElement;/** * Created with IntelliJ IDEA. * User: zhenwei.liu * Date: 13-7-26 * Time: 下午6:53 * To change this template use File | Settings | File Templates. */@XmlRootElement // 标注类名为XML根节点@XmlAccessorType(XmlAccessType.FIELD)   // 表示将所有域作为XML节点public class User {    private long id;    private String username;    private String password;    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}

 

Controller

package com.qunar.controller;import com.qunar.bean.User;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Controller;import org.springframework.stereotype.Repository;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.*;/** * Created with IntelliJ IDEA. * User: zhenwei.liu * Date: 13-7-26 * Time: 下午6:54 * To change this template use File | Settings | File Templates. */@Controller@RequestMapping("/users")public class UserController {    // headers属性标明该方法只接受该Accept头的请求    @RequestMapping(value = "/{id}",            method = RequestMethod.GET)//            headers = {"Accept=text/xml, application/json, application/xml"})    // @ResponseBody 表示返回的对象将转换为客户端Accept头要求的表达形式    // 假如客户端请求头没包含任何形式,则假设客户端可接受任何形式的返回    // 返回的类型匹配方法默认值是先查看URL扩展名,没有扩展名则匹配Accept头,否则匹配defaultContentType    // @PathVariable 表示参数值来自URL,如果参数名与URL括号内形参相同    // 可以省略PathVariable内的参数名    public    @ResponseBody    User getUser(@PathVariable("id") long id) {        User user = new User();        user.setUsername("root");        user.setPassword("root123");        user.setId(id);        return user;    }    // 设置RequestMapping的headers参数标明请求体的内容是json数据    @RequestMapping(value = "/add", method = RequestMethod.POST,            headers = "Content-Type=application/json")    // @ResponseStatus表示响应状态 NO_CONTENT表示无响应内容    @ResponseStatus(HttpStatus.NO_CONTENT)    // 没有配置ViewResolver的情况下@ResponseBody不能省略,否则404    // @RequestBody表示将请求体的数据转为user类    public @ResponseBody void addUser(@RequestBody User user) {        System.out.println(user.getId() + "|" + user.getUsername());    }}

 

dispatcher-servlet.xml

com.qunar.bean.User

 

applicationContext.xml

 

 

web.xml

webAppRootKey
restServer.root
org.springframework.web.util.WebAppRootListener
contextConfigLocation
classpath*:spring/context/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.ContextCleanupListener
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath*:spring/context/dispatcher-servlet.xml
1
dispatcher
/

 

 

另外很重要的是把依赖包配好,否则各种ClassNotDefined

org.codehaus.jackson
jackson-mapper-asl
1.9.12
org.springframework
spring-oxm
3.1.4.RELEASE

 

客户端

import org.springframework.http.HttpEntity;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpMethod;import org.springframework.http.MediaType;import org.springframework.util.LinkedMultiValueMap;import org.springframework.util.MultiValueMap;import org.springframework.web.client.RestTemplate;/** * Created with IntelliJ IDEA. * User: zhenwei.liu * Date: 13-7-26 * Time: 下午10:41 * To change this template use File | Settings | File Templates. */public class Test {    public static String urlGet = "http://localhost:8080/users/{id}";    public static String urlPost = "http://localhost:8080/users/add";    public static RestTemplate rt = new RestTemplate();    // 从Rest接口获取数据    public static void getUser(long userId) {        HttpHeaders headers = new HttpHeaders();        // 设置Accept表示浏览器支持的MIME类型,此处意思是要返回的类型        headers.setAccept(MediaType.parseMediaTypes(MediaType.APPLICATION_XML_VALUE));        HttpEntity requestEntity = new HttpEntity(headers);        System.out.println(                rt.exchange(                        urlGet,                        HttpMethod.GET,                        requestEntity,                        String.class,                        userId                )        );        System.out.println(                rt.getForObject(urlGet, String.class, userId)        );    }    // 传JSON数据到REST接口,自动将JSON数据转化成类    public static void addUserByJson(String userJson) {        HttpHeaders headers = new HttpHeaders();        // 设置ContentType标明数据是JSON数据,否则报415(Unsupported Media Type)        // 此处必须和REST接口的RequestMapping的ContentType对应        headers.setContentType(MediaType.APPLICATION_JSON);        HttpEntity requestEntity = new HttpEntity(userJson, headers);//        System.out.println(requestEntity.getBody().toString());        rt.exchange(urlPost, HttpMethod.POST, requestEntity, null);    }    public static void main(String[] args) {        getUser(1);        addUserByJson("{\"id\":1,\"username\":\"root\",\"password\":\"root123\"}");    }}

输出数据

<200 OK,<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user><id>1</id><username>root</username><password>root123</password></user>,{Server=[Apache-Coyote/1.1], Content-Type=[application/xml], Transfer-Encoding=[chunked], Date=[Sat, 27 Jul 2013 16:02:04 GMT]}>

{"id":1,"username":"root","password":"root123"}

转载地址:http://slzio.baihongyu.com/

你可能感兴趣的文章
QEMU KVM libvirt 手册(1): 安装
查看>>
【LeetCode】35. Search Insert Position (2 solutions)
查看>>
js判断密码强度
查看>>
ASP.NET中使用TreeView显示文件
查看>>
新型I/O架构引领存储之变(四)
查看>>
atitit.元编程总结 o99
查看>>
uniGUI试用笔记(二)
查看>>
HOG特征-理解篇
查看>>
javascript生成n至m的随机整数
查看>>
Microsoft.AlphaImageLoader滤镜解说
查看>>
Could not drop object &#39;student&#39; because it is referenced by a FOREIGN KEY constraint
查看>>
The OpenGL pipeline
查看>>
extjs_02_grid(显示本地数据,显示跨域数据)
查看>>
Tokyo Tyrant(TTServer)系列(四)-tcrmgr远程管理与调试
查看>>
超过响应缓冲区限制
查看>>
SQL基础--&gt; 约束(CONSTRAINT)
查看>>
ubuntu 下安装 matplotlib
查看>>
偶的新的一天
查看>>
webservice的几个简单概念
查看>>
HttpSolrServer 实例管理参考,来自org.eclipse.smila.solr
查看>>