How to Implement a REST Service using Java Servlets

Posted by hdiwan Tue, 30 Oct 2007 20:27:00 GMT

I just realised that Java may have the most organized model for REST that I have most probably ever seen, in the form of servlets. All servlets inherit from a single class which provides distinct methods for various request types, prefixed with "do" and having identical prototypes. For instance, a simple crud application morphed into servlet-form, would read:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DatabaseServlet extends HttpServlet {
  protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // GET provides read functionality
    response.sendRedirect("show.jsp?id="+Db.get(request.getParameter("id"));
  }

  protected void doDelete (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Db.delete(request.getParameter("id"));
    response.sendRedirect("delete.jsp?id="+request.getParameter("id"));
  }

  protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   Result record = Db.edit(request.getParameter("id"))
   record.update(request.getParameterMap());
  }

  protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Result newRec = Db.newRecord();
    newRec.update(request.getParameterMap());
    newRec.save();
  }

Of course, that's a contrived example. The complexity is abstracted to the Db and Result classes, but if those are written, and they most often are, servlets make it extremely simple to web-enable applications.

MLA-style Citation:
Diwan, Hasan "How to Implement a REST Service using Java Servlets" How to Implement a REST Service using Java Servlets. 30 Oct. 2007. Prolific Programmer on the Internets!. 24 Mar. 2008. <http://blog.prolificprogrammer.com/2007/10/30/how-to-implement-a-rest-service-using-java-servlets>.
APA-style Citation:
Diwan, H. (2007, October 30). How to Implement a REST Service using Java Servlets. Retrieved March 24, 2008, from http://blog.prolificprogrammer.com/2007/10/30/how-to-implement-a-rest-service-using-java-servlets.
Chicago-style Citation:
Diwan, Hasan "How to Implement a REST Service using Java Servlets." How to Implement a REST Service using Java Servlets Prolific Programmer on the Internets!. http://blog.prolificprogrammer.com/2007/10/30/how-to-implement-a-rest-service-using-java-servlets (accessed March 24, 2008).

Leave a comment

Comments