@Constoller
@RequestMapping('/api/user')
class UserApi {
@RequestMapping(value = '/{id}', method = RequestMethod.GET)
User get(@PathVariable long id) {
//... load user, etc
}
@RequestMapping(value = '/{id}', method = RequestMethod.POST)
User update(@PathVariable long id, @RequestModel User updated) {
//... load user, update values, etc
}
}
RESTful web服务最近有多流行已经无需我多评价。是的,你的确需要它,但如何选择呢?我尝试了不同的Java REST框架,基本上都是Jersey和Spring MVC。我认为大多数情况下Spring是构建RESTful应用程序的首选。
如果你已经有了一个Spring app,接下来不需要做任何复杂的配置就可以用Spring开始实现RESTful API了。只要使用标准的注解配置向下面这样配置JSON视图解析器(view resolver ):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//这个示例使用了Groovy,相信你能够理解 @Constoller @RequestMapping('/api/user') class UserApi { @RequestMapping(value = '/{id}', method = RequestMethod.GET)
User get(@PathVariable long id) {
//... load user, etc
}
@RequestMapping(value = '/{id}', method = RequestMethod.POST)
User update(@PathVariable long id, @RequestModel User updated) {
//... load user, update values, etc
}
} |
当然,你可以不用JSON转而XML或者使用ProtoBuf以及其他什么。这很简单而且不会因为修改造成代码错误,比起Jersey要简单很多。
通常你的应用程序除了RESTful API还会有其他东西,比如标准的HTML页面、文件下载/上传、复杂的API请需求数据流处理、重要的后台处理、数据库访问、复杂的认证和授权与外部服务集成等等。Spring框架可以将这些完成得很好。同时我最喜欢的就是,通常会有两种办法达成目标:“应急办法”和常规办法:)
实际上我是Grails web的粉丝,我真的很喜欢它并且为Grails写了一些插件。我相信构建传统 web应用方面Grails是最好的框架。但是当我看见采用RESTful构建和一些现代应用之后(大多数是“单页面App”)——我总是会建议使用Spring MVC (+ Groovy,这又是另外一个话题)。
在这个例子中,我们将看到如何使用java.net包实用工具,创建一个访问REST服务RESTful的客户端。当然这不是创建一个RESTful客户端最简单的方法,因为你必须自己读取服务器端的响应,以及Json和Java对象的转换。
请求Get
public class JavaNetURLRESTFulClient {
private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/print/Jamie";
public static void main(String[] args) {
try {
URL restServiceURL = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept", "application/json");
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
System.out.println("Output from Server: \n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行后输出结果是:
Output from Server: {"id":1,"firstName":"Jamie","age":22,"lastName":"Diaz"}
POST提交:
public class JavaNetURLRESTFulClient {
private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";
public static void main(String[] args) {
try {
URL targetUrl = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下载地址:http://pan.baidu.com/s/1dD5lhtR
一些有用的链接:
- Spring – http://www.springsource.org/spring-framework
- Spring安全项目,如果你需要使用认证–http://www.springsource.org/spring-security
- 所有Spring项目 – http://www.springsource.org/projects
- 如果真的打算做一个好的RESTful应用,你需要Spring HATEOAS –https://github.com/SpringSource/spring-hateoas
- Spring MVC文档 –http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html
- 一篇使用Spring进行内容交互的好文 –http://blog.springsource.org/2013/05/11/content-negotiation-using-spring-mvc/
原文链接: igorartamonov.com 翻译: ImportNew.com - 唐尤华
译文链接: http://www.importnew.com/5163.html
相关推荐
使用Spring 实现RESTful Web 服务 demo
用Spring maven做的restful api小Demo 仅供参考 看见有其他大神做的,积分太高了,我来个免积分下载的吧 ,不敢忘挖井人http://blog.csdn.net/u010857795/article/details/54377196 附上...
现在网上大多数关于restful的资料都是spring3,而spring4进行了一些更改,在此处上传一个基本demo供参考,由于此demo使用的IDE是intellj12,使用其它工具的将配置文件、控制器、包拷入使用即可。
Spring Boot 整合 Mybatis 实现RESTful API ,具体可以查看博客: http://blog.csdn.net/yaozhiqi1905658804/article/details/70820892
利用CXF3.0.2+Spring3.2.14发布RESTFul,传递json数据格式的!需要源代码可以下载!
利用Spring对RESTful Web Service进行简单的实现demo。
Spring Boot 2精髓带书签目录高清版,文字可复制,内容丰富,涵盖Spring Boot框架、Spring MVC、视图技术、数据库访问技术,并且介绍多环境部署、自动装配、单元测试等高级特性,包括使用Spring实现RESTful架构,在...
另一方面,当系统模块增加,性能和吞吐量要求增加时,如何平滑地用Spring Boot实现分布式架构,也会在本书后半部分介绍,包括使用Spring实现RESTful架构,在Spring Boot框架下使用Redis、MongoDB、ZooKeeper、...
本文将介绍如何使用Spring创建Java实现的服务器端RESTful Web Services。这个例子将使用浏览器、curl和Firefox插件RESTClient作为发出请求的客户端。 本文假定您是熟悉REST基本知识的。 Spring 3的REST支持 ...
RESTful Web Service 是一个使用 HTTP 和 REST 原理实现的 Web Service。通常,一个 RESTful Web Service 将定义基本资源 URI、它所支持的表示/响应 MIME,以及它所支持的操作。
SpringBoot+Mybatis+CXF框架,实现Restful api与 WebService api接口的大实验
CXF+spring+restful创建一个web的接口项目源代码,添加了restful实现的配置及jar包
1.内容丰富,涵盖Spring Boot框架、Spring MVC、视图技术、数据库访问技术,并且介绍多环境部署、自动装配、单元测试等高级特性,包括使用Spring实现RESTful架构,在Spring Boot框架下使用Redis、MongoDB、ZooKeeper...
完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip 完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip 完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统...
最近在搞springboot的模块化开发,集成了shiro+jwt实现restful接口的token认证。 需新增测试表: CREATE TABLE `t_user` ( `user_id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT, `user_name` varchar(32...
另一方面,当系统模块增加,性能和吞吐量要求增加时,如何平滑地用Spring Boot实现分布式架构,也会在本书后半部分介绍,包括使用Spring实现RESTful架构,在Spring Boot框架下使用Redis、MongoDB、ZooKeeper、...
本案例采用jpa 持久化,/auth/login 获取token登入信息,把token 前添加Bearer 注意Bearer 后有个空格,放到headers 请求中.可访问其他信息
spring整合cxf实现restful的webservice服务,代码分为服务端和客户端两个模块;服务端为接口,客户端为接口调用。
基于 Java Spring 将上述类的方法对外提供 RESTful 服务并调用 2019-12-23根据全网的教程搭建最详细的教程 源码太大上传不了,但是教程内容十分详细,跟着我的教程一步一步就可以搭建起来,很坑的地方也说明了。
在本示例中,我们将向您展示如何将对象转换成json格式并通过spring mvc框架返回给用户。 使用技术及环境: Spring 3.2.2.RELEASE Jackson 1.9.10 JDK 1.6 Eclipse 3.6 Maven 3 PS:在spring 3 中,要输出json...