Using custom Java methods in JSP

Posted on 16-03-2013 11:21 by graham
This tutorials shows how to make use of your own custom and built in Java functions/methods in JSP.

Creating your method


Let's say you have the following utility class that contains a method for date formatting:
FormatUtil.java
public class FormatUtil
{
public static String formatDate (Date date, String format)
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
}

Now, you want to use the FormatUtil.formatDate method in your JSP page. The way to do this is to make it available through a custom tag library.

Create a tag library


In your project, create a file called my-functions.tld. It can be placed anywhere under the WEB-INF folder, preferably in /WEB-INF/tld/my-functions.tld.
my-functions.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">

<display-name>My functions</display-name>
<tlib-version>1.0</tlib-version>
<uri>http://mydomain.com</uri>

<function>
<name>formatDate</name>
<function-class>my.utils.FormatUtil</function-class>
<function-signature>java.lang.String formatDate(java.util.Date, java.lang.String)</function-signature>
</function>
</taglib>

Using the function


To use the function in a JSP page, you need to declare the taglib at the beginning of the page:
<%@ taglib prefix="my-fn" uri="/WEB-INF/tld/my-functions.tld" %>

and then use it, e.g. like this:
<input type="text" value="${my-fn:formatDate(currentDate, "dd-MM-yyyy")}"></input>
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems