Spring实现RESTful

 
//这个示例使用了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
}
}

 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

一些有用的链接:

原文链接: igorartamonov.com 翻译: ImportNew.com - 唐尤华
译文链接: http://www.importnew.com/5163.html

相关推荐