---
title: "【虎.无名】自定义Java的REST行为分发器"
author: "zeroliu"
date: "2008-09-10T09:10:28Z"
tags: []
slug: "java-rest"
draft: false
lastmod: "2008-09-10T09:10:28Z"
id: 240006
url: "https://zeroliu.iteye.com/blog/240006"
---

【虎.无名】在Restlet和Rails中，资源所支持的Action操作是不一致的。Restlet支持4个操作，而Rails支持的则多了index等几个。前者与某个具体id资源对应，后者与一类资源对应。后者更简洁一些。  
*1，GET /users 列表所有用户*  
*2，POST /users 创建新用户（此时id尚未确定）*  
*3，GET /users/{id} 显示（与id对应的）某用户*  
*4，PUT /users/{id} 更新（与id对应的）某用户（不存在，则创建，与“2，POST”类似）*  
*5，POST /users/{id} （扩展定义，与“4，PUT”等效，针对不支持PUT的服务器）*  
*6，DELETE /users/{id} 删除（与id对应的）某用户*  
*7，GET /users/{id}/orders 列表（与id对应的）某用户的所有订单*  
*8，POST /users/{id}/orders 创建（与id对应的）某用户的新订单*  
*9，GET /users/{id}/orders/{orderid} 显示（与id对应的）某用户的某个订单*  
【虎.无名】我的设想是参考Rails机制，定义自己的路由映射机制，自定义Servlet来解析如下5个操作。（注意：里面doList没有考虑根据某些条件来查询，因而没有req参数。只有doUpdate需要req参数）

```
protected abstract void doList(HttpServletResponse res, Map uriAttr) throws IOException,ServletException;
protected abstract void doCreate(HttpServletResponse res, Map uriAttr) throws IOException,ServletException;
protected abstract void doShow(HttpServletResponse res, Map uriAttr, String id) throws IOException,ServletException;
protected abstract void doDelete(HttpServletResponse res, Map uriAttr, String id) throws IOException,ServletException;
protected abstract void doUpdate(HttpServletResponse res, Map uriAttr, String id, HttpServletRequest req) throws IOException,ServletException;
```

 //REST行为分发器

```
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
   _log.debug("# service(HttpServletRequest)...", req.getRemoteAddr());
   String method = req.getMethod();
   String id = this.getId();
   if (null==id) {
    if(method.equalsIgnoreCase("GET")) {//1，GET /users 列表所有用户
     this.doList(res, _uriAttr);//缺省(无法定义参数，可以考虑在body中定义参数，但这样破坏了资源的一致性。)
    }else if (method.equalsIgnoreCase("POST")) {//2，POST /users 创建新用户（此时id尚未确定）
     this.doCreate(res, _uriAttr);//创建，此时id尚未确定
    }else {
     res.sendError(HttpConst.CLIENT_ERROR_Method_Not_Allowed);
    }   
   }else {
    if (method.equalsIgnoreCase("GET")) {//3，GET /users/{id} 显示（与id对应的）某用户
     this.doShow(res, _uriAttr, id);
    }else if (method.equalsIgnoreCase("PUT")) {//4，PUT /users/{id} 更新（与id对应的）某用户（不存在，则创建，与“2，POST”类似）
     this.doUpdate(res, _uriAttr, id, req);
    }else if (method.equalsIgnoreCase("POST")) {//5，POST /users/{id} （扩展定义，与“4，PUT”等效，针对不支持PUT的服务器）
     this.doUpdate(res, _uriAttr, id, req);//此时id已经确定，针对此URI可替代PUT方法
    }else if (method.equalsIgnoreCase("DELETE")) {//6，DELETE /users/{id} 删除（与id对应的）某用户
     this.doDelete(res, _uriAttr, id);
    }else { //缺省行为！
     res.sendError(HttpConst.CLIENT_ERROR_Method_Not_Allowed);
    }
   }
}
```

 （待续）  
**原贴**：[http://hi.baidu.com/zeorliu/blog/item/ca3a3997ab79ac6b55fb96c2.html](http://hi.baidu.com/zeorliu/blog/item/ca3a3997ab79ac6b55fb96c2.html) 2008-09-08 17:59【虎.无名】自定义Java的REST行为分发器  
**参考**：  
[http://hi.baidu.com/821115/blog/item/e6df10f03a9efdada50f520f.html](http://hi.baidu.com/821115/blog/item/e6df10f03a9efdada50f520f.html) 传统的Java Web MVC框架距离REST有多远  
【虎.无名】（评论）Restlet作者认为servlet是过度设计，因而重新定义了一套API，后来我发现，restlet本身也似乎过度设计了，连MediaType都使用了特定的类来表示，请求也没有获取charset的方法，getText()获取没有字符集参数，因而支持中文很困难。JRest4Guice则是一个国产开源项目(项目地址： [http://code.google.com/p/jrest4guice/](http://code.google.com/p/jrest4guice/) 这个项目借鉴了[http://www.iteye.com/topic/170289](http://www.iteye.com/topic/170289) 的一些思想和代码)，使用Guice作为容器（因而要求jdk5环境），基于Servlet来实现REST开发。不过作者最近半年也没怎么更新了。其中路由映射机制倒是给我了一些参考。不过，我感觉，不应该根据http的method来分发请求，而应根据REST特点行为来分发请求。  
[http://cnoss.iteye.com/blog/176755](http://cnoss.iteye.com/blog/176755) 2008-03-27 向大家推荐一个轻量级的java rest 框架 JRest4Guice  
[http://www.iteye.com/topic/201103](http://www.iteye.com/topic/201103) 一个Java的Restful服务框架（JRest4Guice），支持JPA、JAAS、分布式资源对象  
[http://www.iteye.com/topic/170289](http://www.iteye.com/topic/170289) 2008-03-11 超轻量的REST“框架”：目前唯一的功能就是实现REST风格的URL映射以及不同的HTTP方法（GET，POST，PUT和DELETE）对资源类的方法的映射，框架的使用很简单。 【虎.无名：是JRest4Guice的最初原型】  
[http://www.ibm.com/developerworks/cn/xml/x-restfulsoa/index.html](http://www.ibm.com/developerworks/cn/xml/x-restfulsoa/index.html) 2008年3月06日：使用 XML 实现 REST 式的 SOA，简化面向服务和XML序列化 【虎.无名：这是上面超轻量的REST“框架”的灵感来源】  
[http://www.iteye.com/topic/85928](http://www.iteye.com/topic/85928) 2007-06-02 （dlee）Java REST框架一览  
[http://www.iteye.com/topic/70113](http://www.iteye.com/topic/70113) 2007-04-11 关于REST的一点想法，欢迎大家讨论。