Tag Archives: jsp

Using JSP On Spring Boot App

By default Spring Boot did not come with JSP support. Here’s how to set your app to use JSP:

  1. Set the project to use tomcat7-maven-plugin rather than spring-boot-maven-plugin
  2. Add / ensure following Maven dependencies are setup
    
      org.springframework.boot
      spring-boot-starter-tomcat
      provided
    
    
      org.apache.tomcat
      tomcat-jsp-api
      provided
    
    
      javax.servlet
      jstl
    
    
  3. The Web MVC auto configuration feature of Spring Boot sets you up with a ViewResolver with blank suffix and prefix, hence you can place jsp in src/main/webapp/WEB-INF/test.jsp and have your controller return path to it
    
    ("/test")
    public class TestController {
      (method = GET)
      public String test() {
        return "/WEB-INF/test.jsp";
      }
    }
    

Hope this helps!

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:


Jim
34


Bob
30


Susan
28

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


  
    ${user.name}
    ${user.age}
  

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 if 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" %>



  
    
    
    
  

  
    
  

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" %>

  
    
  
  
    

Hello World

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 %>
My Cool Website


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" %>

  
    
  
  
    

Hello world!

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" %>
${thetitle}


And the title attribute can be set on the including page


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

campaignA.tag

<%@ tag %>

campaignB.tag

<%@ tag %>

marketing.tag

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


login.jsp

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

Another useful application of JSP tag is when including javascript. Having multiple 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.

Using Fragment Attribute

Another neat trick is to use fragment attribute. Say you want to build a html template with customized body element:

template.tag

<%@ tag %>
<%@ attribute name="header" fragment="true" %>
<%@ attribute name="body" fragment="true" %>

  
    My Website
    
  
  
    
  

home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="mytag" %>

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

Spring MVC File Upload Form

Objective : Setup a form with file upload field

Environment

  • 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.


File:

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

fileuploadform

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


  commons-fileupload
  commons-fileupload
  1.3

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)


  

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

(value = "/", method = RequestMethod.POST)
public String upload(("myfile") MultipartFile myFile) {
  logger.info("Received file of size " + myFile.getSize() + " bytes");
  InputStream inputStream = myFile.getInputStream();
  // .. do something with inputStream
  inputStream.close();
  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:

mycoolapp.war
  +-resources
    +-images
    | +-logo.jpg
    +-css
    | +-common.css
    | +-login.css
    +-js
      +-jquery.min.js

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


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.


The method that has worked best for me so far is by using JSP’s 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" %>


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