Thursday 11 December 2014

Tips for RESTful web apps using Servlets

Here are a few tips on how to make the most of the Servlet container's natural RESTful architecture.
  1. Let each servlet represent a 'resource' in your system. You can then override the doGet(), doPost(), doDelete() etc methods to add possible operations, if that resource needs to support them.
  2. HTML forms that perform changes on the server must use the POST method and links to read-only pages and search forms must use the GET method. Most browsers won't let you use PUT or DELETE as form methods, so these type of calls need to be made via AJAX.  If you try to use the body of the http call to pass parameters, these will be ignored by the server unless you are using POST. So PUT, GET and DELETE calls need to pass all their information in the URL.
  3. You can make pretty urls by using the URL mapping provide by the servlet container but you can only use the wildcard * at the end of the URL pattern. This means you can't use the URL to pass hierarchical information. So for example you would have to use app/papers/16 rather than apps/users/jsmith/papers/16. A hierarchical URL is not necessary for RESTful architecture anyway, since REST does not dictate any URL format.
  4. Any URLs used by your system should be devised on the server and passed down to the client as links or form actions. This ensures a clean separation of client and server, allowing you to change the format of the urls without changing the client code too much.

No comments:

Post a Comment