用純Servlet實現一個REST“框架”,就這么簡單

jopen 10年前發布 | 61K 次閱讀 REST Servlet Java開發

/**

  • 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();
      

      } } }</pre>


      /**

  • 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();
    

    } }</pre>


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

    } }</pre>


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!