This is a single archived entry from Stefan Tilkov’s blog. For more up-to-date content, check out my author page at INNOQ, which has more information about me and also contains a list of published talks, podcasts, and articles. Or you can check out the full archive.

Getting by with just Servlets and JSPs

Stefan Tilkov,

Bill de hÓra wonders how to use Servlets and JSPs without having to treat URIs like it’s 1999:

However it’s easy to forget that Servlets were Java’s response to CGI, way back when. Here’s is the link for Stefan’s entry:

            /blog/st/2007/08/15/java_web_frameworks.html

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?

Something like this?

    import javax.servlet.http.*;

public class Blog extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response) {
try {
String path = request.getPathInfo();
// do something fancy with the path, like decomposing it into
// parts, retrieving the entry from the DB, creating an entry object,
// and setting it as a request attribute
// simulated here :-)
request.setAttribute("entry", "Entry with ID " + path);
getServletConfig().getServletContext().getRequestDispatcher("/internal/_entry.jsp").forward(request, response);
// Assumption: _entry.jsp will format the content from the entry
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}

This servlet would be deployed e.g. at /blog/st/*, and could handle all URIs that start this way, so 2007/08/15/java_web_frameworks.html would simply be returned by getPathInfo(). Of course any decent Java programmer could not help but create at least a small library to help with this, but that’s a far cry from a full-featured open source over-hyped Web framework …

Update: Here are two posts from Ian Griffiths showing something similar for the .NET-inclined (via Dilip via email).

Yet another update: Hugh Winkler has a nice micro-framework for the purpose.