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:
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.
<?xml version="1.0" encoding="UTF-8" ?>

<display-name>My functions</display-name>

<function-signature>java.lang.String formatDate(java.util.Date, java.lang.String)</function-signature>

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>


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
+ 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