简体   繁体   中英

How to create a RESTful Web Service using Servlet (without Jersey, etc)?

如何在不使用任何JAX-RS实现(Jersey等)的情况下使用Servlet创建RESTful Web服务?

Basically you absolutely right, you don't need a framework in order to implement REST API.

For instance, you could do basic crud operations in simple servlet class, like this:

@WebServlet(urlPatterns = "/book/*")
public class BookServlet extends HttpServlet {
   @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response) {
     // fetch from db
   }
   @Override
   public void doPost(HttpServletRequest request, HttpServletResponse response) {
     //update
   }
   @Override
   public void doDelete(HttpServletRequest request, HttpServletResponse responce) {
    //delete
   }
}

It's a little bit inconvenient since you need to manually parse url params, do serialization, but under the hood, JAXRS and Spring MVC is just a servlets! So, if you don't want dependencies in your code, I could suggest to just implement some convenient wrappers over servlet api.

Tip: you could parse path params from request like this:

String info = request.getPathInfo(); 
String[] parts = pathInfo.split("/");
String param1 = pathInfo[0];

So, for instance, if you have request like this: HTTP GET /book/{id} You'll get {id} in param1 which can be later used in database lookup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM