How to create a custom Function for JSTL

standard
27.04.2010 Posted in Java 2 Comments

So just a quick post. How do we create a custom function for JSTL.

Let’s begin.

1. Create a .tld file under /WEB-INF

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" 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">
    <tlib-version>1.0</tlib-version>
    <short-name>mytlds</short-name>
    <uri>http://www.noppanit.com/myTlds</uri>
    <function>
        <name>charAt</name>
        <function-class>com.nc98.expressions.Functions</function-class>
        <function-signature>char charAt(java.lang.String, int)</function-signature>
    </function>
</taglib>

2. Create a class

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.nc98.expressions;

/**
 *
 * @author freaking_crack
 */

public class Functions
{
    public static char charAt(String input, int index)
    {
        return input.charAt(index);
    }
}

3. And then use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.noppanit.com/myTlds" prefix="mt" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
            ${mt:charAt("AB",0)} <!-- It will give you A-->
    </body>
</html>
  • Nasarudin Abdullah

    Excellent… straightforward and 1 minute tutorial.

  • Rakib Shahriar

    Superb article. Helped me a lot. Thanks.