JSP Date Snippet

Posted on

Being a traditionalist, I tend to forget some of the things you can do with tag libraries like JSTL above and beyond simple things like outputting information. A colleague asked me about putting the current year on a page and my first response was something like this:

<%@ page import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
  Date date = new java.util.Date();
  pageContext.setAttribute("date", date);
<c:set var="date" value="${date}" />
<fmt:formatDate pattern="yyyy" value="${date}" />

It’s quite obvious looking at it that there’s a bit of redundancy in setting the date with a scriptlet and then making it available to JSTL to output with the Format tag library. That’s when I came across the solution to use the JSP useBean tag with JSTL resulting in the much simpler solution as follows:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<jsp:useBean id="now" />
<fmt:formatDate var="year" value="${now}" pattern="yyyy" />
<c:out value="${year}" />

I don’t believe it has any version dependencies (as I’ve encountered with some of the JSTL libraries that only work with the JSP 2.0 spec and the like) and certainly feels cleaner. Most importantly, it gets rid of the scriptlet and, in the JSP world, that’s a win.

Leave a Reply

Your email address will not be published. Required fields are marked *