16 August 2007
REST with JSP
I was interested to read Bill de hÓra’s question about whether servlets and JSP can be used to create a RESTful application without resorting to RPC-style URIs like:
http://www.innoq.com/blog/entry.jsp?id=java_web_frameworks
Absolutely yes! A beauty for me of the web side of Java EE is that the URI can take any format you like. So, to use a URI like:
http://www.innoq.com/blog/st/2007/08/15/java_web_frameworks.html
we could work as follows.
- The externally facing URI is probably mapped by a reverse proxy or content switch (or the like) to the blogging application on a Java EE application server. The internal URI might be something like:
http://s012.innoq.com/javablog/blog/st/2007/08/15/java_web_frameworks.html
- The application server might interpret the URI like this:
/javablog: Root web context of the Java blogging application.
/blog: Part of the URI that maps to a servlet for serving all blog pages. In
web.xmlit may be mapped with:<servlet> <servlet-name>BloggingServlet</servlet-name> <servlet-class>com.innoq.blogging.web.BloggingServlet</servlet-class> ... </servlet> <servlet-mapping> <servlet-name>BloggingServlet</servlet-name> <url-pattern>/blog*</url-pattern> ... </servlet-mapping>
Further work continues in the servlet’s
doGetmethod./st/2007/08/15/java_web_frameworks.html: This string is available to the servlet using
request.getPathInfo(). - The servlet tokenises the string and works with the information. For example
stis used to brand the blog as belonging to Stefan Tilkov,2007,08and15are date identifiers andjava_web_frameworksis the post slug, with.htmlto indicate that the content type of the response is text/html. - The servlet uses that information to retrieve the post from the persistence store and assembles request-scope objects that will be used by the JSP.
- The servlet forwards to the JSP, which templates the HTML response. For example:
request.getRequestDispatcher("/WEB-INF/jsp/blog_post.jsp").
forward(request, response);The JSP is never called via a URI that maps to its directory structure. It can (as in this example) reside under the WEB-INF directory, which cannot be mapped to a URI path.
Caching? That can be done by the servlet or by the application server or somewhere in front of that. Or publishing a post may result in the creation of an HTML file on disk in a directory structure that maps directly to the URI.

Servlets+JSP design answers
Earlier I asked: “I’m wondering how would one produce a URL space for a blog style archive, using Servlets+JSP, and do so in a way that isn’t a CGI/RPC explicit call?” I got some answers, all good: Sam Ruby: “Perhaps…
very interesting, but I don’t agree with you
Idetrorce