The wonders of Java 5 + Servlets

I love servlets. I love not having to use query strings. Servlets (done right) make web programming a dream. The problem is: Almost every servlet I write is mapped to a directory. I recently started working on a forum system (for fun), and with it, I’ve wound up writing a rather interesting piece of code. It maps the path info of your servlet to a specific method. Here’s the first bit of code from the “list forums” servlet:

@EnsureIndex(value="/page1.html",ensureMatch=true)
public class ForumListServlet extends BaseServlet {
    private static final Integer
        NO_PAGE_FOUND = new Integer(1);

    public void init() throws ServletException {
        addPageMapping(NO_PAGE_FOUND,
                "/WEB-INF/jsp/list/nopage.jsp");
    }

    @PatternHandler("/page${pageIndex}.html")
    public void list(HttpServletRequest req,
        HttpServletResponse resp)
        throws ServletException, IOException
    {
        String pageIndex = req.getParameter("pageIndex");
        int pageNumber = -1;

        try {
            pageNumber = Integer.parseInt(pageIndex);
        } catch(NumberFormatException ex) {
            forward(NO_PAGE_FOUND, req, resp);
            return;
        }

...
    }
}

So what this code shows is that if the path-info part of the URL (the part after the servlet path) doesn’t match the regex “/page.*\.html”(in Java notation), then send the browser a redirect to “/page1.html”. So if I mapped this servlet to “/forum/list/*” (which is where it lives in my forum app), and then entered the URL “/forum/list/index.html” I would get a redirect to “/forum/list/page1.html”. The “pageIndex” parameter in my HttpServletRequest (which normally reflects the parameters of the Query string (it still does… but also includes your extra path bits)) will reflect the part that is “${pageIndex} in my “@PatternHandler” annotation. If I don’t use the “ensureMatch=true” in my “@EnsureIndex” annotation, then the default “service” (and in tern doGet, doPost, etc.) will be invoked if a method with “@PatternHandler” cannot be found to handle a request.

The whole thing about “page-mapping” is just a convenient way to forward to the JSP’s that do the actual HTML rendering work. I make extensive use of JSTL, JSP EL and my own custom JSP tags, I don’t think I’ve had even one line of Java code in my JSP’s in ages. I love custom tags to much.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: