A RESTful Service as an HttpServlet

Chapter 1 has a sample RESTful service implemented as a JSP script and two backend classes: Prediction and Predictions. The JSP-based service supported only GET requests. This section revises the example to provide an HttpServlet implementation with support for the four CRUD operations:

  • A new Prediction can be created with a POST request whose body should have two key/value pairs: a who key whose value is the name of the predictor and a what key whose value is the prediction.
  • The Prediction objects can be read one at a time or all together with a GET request. If the GET request has a query string with an id key, then the corresponding Prediction, if any, is returned. If the GET request has no query string, then the full list of Predictions is returned. On any GET request, the client can indicate a preference for JSON rather than the default XML format.
  • A specified Prediction can be updated with a PUT request that provides the identifier for the Prediction and either a new who or a new what.
  • A specified Prediction can be deleted.

The earlier JSP service is predictions and the servlet revision is predictions2. The structure of predictions2 differs from that of predictions in several ways. The most obvious change is that an explicit HttpServlet subclass replaces the JSP script. There are also changes in the details of the Prediction and Predictions classes, which still provide backend support. The details follow.

Get Java Web Services: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.