JSP JSTL Using varStatus to Add CSS Class On Last Element

Often when iterating a collection to display it on table specific css class need to be added to the last row for styling purpose, eg:

<tr class="last"><td>Susan</td><td>28</td></tr>

This can be achieved on JSP JSTL core tag by using varStatus attribute:

<c:forEach var="user" items="${users}" varStatus="status">
  <tr ${status.last ? 'class="last"' : ''}>

On varStatus you define what is the variable name which will hold the loop iteration status. This variable then contain information whether or not we’re on the last iteration, and place specific content accordingly. See the javadoc reference for LoopTagStatus for more info.

The question mark and colon syntax ${status.last ? 'class="last"' : ''} is similar to standard Java syntax. It will print the content class="last" only is status.last is true (ie: we’re on the last iteration of loop)


HTML Page Template Using JSP Tag

Apart from simple attribute, JSP also provides fragment tag feature. This can be used to create HTML page template.

Below is an example /WEB-INF/tags/page-template.tag file with two fragment attributes declared: header and content.

<%@ attribute name="header" fragment="true" %>
<%@ attribute name="content" fragment="true" %>
<!DOCTYPE html>

    <!-- Place Common CSS here -->
    <!-- Common JS here -->
    <jsp:invoke fragment="header"/>

    <jsp:invoke fragment="content"/>

Now you DRY yourself by reusing this template on your JSP pages. Below is a sample home.jsp:

<%@ taglib tagdir="/WEB-INF/tags" prefix="mycoolsite" %>
  <jsp:attribute name="header">
    <!-- Page specific JS / CSS goes here -->
  <jsp:attribute name="content">
    <h1>Hello World</h1>

Read more about JSP custom tag on the Official Java EE Tutorial.

Creating Reusable HTML Using JSP Tag

Revisiting the almighty DRY (Do not Repeat Yourself) principle of software programming, reusing HTML elements can be done via JSP tags. One obvious application is when including common css, javascript etc on your html header.

Firstly create a .tag file containing the reusable code. In here I created /WEB-INF/tags/myheader.tag

<%@ tag %>
<title>My Cool Website</title>
<link rel="stylesheet" href="resources/common.css"/>
<script type="text/javascript" src="resources/common.js"><!-- --></script>

And now I can use this anywhere else I need it. Just declare the tag prefix and location and place it

<%@ taglib prefix="wohoo" tagdir="/WEB-INF/tags" %>
    <h1>Hello world!</h1>

The tag can also be parametrized to inject it with different settings. Declare the attribute like this in the tag file:

<%@ tag %>
<%@ attribute name="thetitle" %>
<link rel="stylesheet" href="resources/common.css"/>
<script type="text/javascript" src="resources/common.js"><!-- --></script>

And the title attribute can be set on the including page

<wohoo:myheader thetitle="My Cool Website"/>

Of course, the tag can be nested too. Below code will produce the image of both campaignA and campaignB just by simply using <my:marketing/> tag.


<%@ tag %>
<img src="campaignA.jpg"/>


<%@ tag %>
<img src="campaignA.jpg"/>


<%@ tag %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>


<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>

Another useful application of JSP tag is when including javascript. Having multiple <script src="myscript.js"> tags can slow down load time of your website as each of them require one HTTP request. If you use JSP tag instead, you can still separate the file but when it’s rendered to the browser it will appear as if the scripts were inline.

Read more about JSP custom tags on Java EE 5 Tutorial.

Spring MVC File Upload Form

Objective : Setup a form with file upload field


  • Spring MVC 3.2.3.RELEASE
  • Commons Fileupload 1.3

First let’s code the JSP view of the form. Note below enctype=”multipart/form-data” setting is important, it tells the browser to post the form data as multipart.

<form method="post" enctype="multipart/form-data">
  File: <input type="file" name="myfile"/><br/>
  <button type="submit">Upload</button>

Above JSP will result in a simple file upload form like this:


Then add commons-fileupload 1.3 maven dependency to your pom.xml:


And configure CommonsMultipartResolver on your spring context. The bean id name is important. Also below I configured it to have maximum file size of 1 mb (1000000 bytes)

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="1000000"/>

Now we’re ready to code the controller handler method. The uploaded file is automatically bound into a MultiPart object from which you can obtain input stream.

@RequestMapping(value = "/", method = RequestMethod.POST)
public String upload(@RequestParam("myfile") MultipartFile myFile) {
  logger.info("Received file of size " + myFile.getSize() + " bytes");
  InputStream inputStream = myFile.getInputStream();
  // .. do something with inputStream
  return "home";

Looking Up Context Path On a JSP Page

Supposed you have a cool web application running on http://mycompany.com/mycoolapp and you have few static resources such as CSS, images and javascripts under resources folder:

    | +-logo.jpg
    | +-common.css
    | +-login.css

One common issue that appear is you can’t simply reference these static resources using relative path from your JSP page like this:

<img src="resources/images/logo.jpg"/>

Although in many cases it works fine, but if you have multi level URLs like http://mycompany.com/mycoolap/login, http://mycompany.com/mycoolap/users/1234 the relative path would be different for each, which means your code isn’t reusable.

Putting a slash “/” in front of the path to make it semi-absolute isn’t always a good idea either because if the context-path name changes all your references are broken.

<img src="/mycoolapp/resources/images/logo.jpg"/>

The method that has worked best for me so far is by using JSP’s <c:set ..> tag. First ensure you have declared the jstl core tag at the top of your JSP page, and create a “root” variable like this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="root" value="${pageContext.request.contextPath}"/>

Now the JSP variable “root” always refers to your context path, you can use it to reference your static resource like this:

<img src="${root}/resources/images/logo.jpg"/>