用纯Servlet实现一个REST“框架”,就这么简单

jopen 10年前

/**   * REST请求分派器   */  @WebServlet(name = "Dispatcher", urlPatterns = "/rest/*")  public class Dispatcher extends HttpServlet {      /**       * URL与请求处理器的映射       */      private Map<Pattern, Class> handlers = new HashMap<Pattern, Class>() {{          put(Pattern.compile("^/devices/([^/]+)$"), DeviceHandler.class);      }};        @Override      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          try {              boolean matched = false;              String path = request.getPathInfo();              for (Pattern pattern : handlers.keySet()) {                  Matcher matcher = pattern.matcher(path);                  if (matcher.lookingAt()) {                      int groupCount = matcher.groupCount();                      String[] args = new String[groupCount];                      if (groupCount > 0) {                          for (int i = 0; i < matcher.groupCount(); i++) {                              args[i] = matcher.group(i + 1);                          }                      }                      Class handlerClass = handlers.get(pattern);                      Object handlerInstance = handlerClass.newInstance();                      handlerClass.getField("request").set(handlerInstance, request);                      handlerClass.getField("response").set(handlerInstance, response);                      handlerClass.getMethod(request.getMethod().toLowerCase(), String[].class).invoke(                              handlerInstance,                              (Object) args                      );                      matched = true;                      break;                  }              }              if (!matched) {                  throw new Exception(String.format("No handler found to deal with path \"%s\"", path));              }          } catch (Exception ex) {              response.setStatus(500);              response.setContentType("text/plain;charset=UTF-8");              PrintWriter out = response.getWriter();              ex.printStackTrace(out);              out.flush();              out.close();          }      }  }


/**   * REST请求处理器   */  public abstract class Handler {      public HttpServletRequest request;      public HttpServletResponse response;        public void get(String[] args) throws Exception {          throw new Exception("Not implemented");      }        public void post(String[] args) throws Exception {          throw new Exception("Not implemented");      }        public void put(String[] args) throws Exception {          throw new Exception("Not implemented");      }        public void delete(String[] args) throws Exception {          throw new Exception("Not implemented");      }        public void writeJsonObject(Object object) throws Exception {          response.setContentType("application/json;charset=UTF-8");          PrintWriter out = response.getWriter();          out.println(Json.dump(object));          out.flush();          out.close();      }  }


/**   *   */  public class DeviceHandler extends Handler {      @Override      public void get(String[] args) throws Exception {          Map ret = new HashMap();          List result = Db.query("select id, name, description from devices");          for (Object record : result) {              Object id = ((Map) record).get("id");              Map device;              if (!ret.containsKey(id)) {                  device = new HashMap();                  ret.put(id, device);              } else {                  device = (Map) ret.get(id);              }              device.put("name", ((Map) record).get("name"));              device.put("description", ((Map) record).get("description"));          }          writeJsonObject(ret);      }  }