Using JSTL custom tags to place SVGs and organise your JSP templates

One of the problems I’ve faced dealing with creating JSP templates is that they easily get out of hand. Sure, you can use includes to divide your template into multiple files but that still might look cumbersome.

Luckily JSTL provides an option of creating own tags. They can have some logic in them and their usage is very concise. To create your own JSTL tag make a new file with a .tag extension e.g. textScore.tag

<%@ tag body-content="empty" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ attribute name="score" rtexprvalue="true" required="true" type="java.lang.Float" %> 

<c:if test="${score >= 3}">
    <c:out value="Good"/>
</c:if>
<c:if test="${score < 3}">
    <c:out value="Bad"/>
</c:if>

Where the “score” is a variable you’d normally use all over your template. Then in the main template file you have to declare that you’ll be using custom tags, point to their location and specify their prefix:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="myTag" tagdir="/WEB-INF/tags/"%>

Then in the body of your template you use your tag like this (notice the name of the tag’s file after the prefix):

<myTag:textScore score="${rating.score}" />

The same goes for SVG images. Create a starsScore.tag.

<%@ tag body-content="empty" %> 
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ attribute name="score" rtexprvalue="true" required="true" type="java.lang.Float" %> 

<c:set var='full' scope='page' value='<img alt="full star" src="/img/fullStar.svg" /> ' />
<c:if test="${score > 4.5}">
    <c:out value="${full}${full}${full}${full}${full}" escapeXml="false"/>
</c:if>

This way you can have one custom tag to use all over your website for placing ratings represented as SVG stars. The code above would insert five of them for a score of more than 4,5.

You’d invoke it with <myTag:starsScore score ="${rating.score}" />
If you ever want to change your graphics or the logic behind scoring e.g. by using halves then you only have to edit your custom tag.