| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
11年前发布

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

/**   * 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);      }  }


 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1395796511353.html
REST Servlet Java开发