Saturday, May 07, 2011

Custom JSP Tags to find if a String is Numeric

JSP scriptlets should be avoided (Even though I confess I have used them for years) especially to avoid Null Pointer Exceptions in JSP.

There are many JSP tag libraries with a lot of functionality already implemented but no matter how much is already there you can always have a scenario where the function simply does not exist in any of the existing tag libraries.

In those cases you need to define a Custom Taglib. This is actually easy and I will demonstrate here how to use a custom taglib to implement a function to find out if a String is numeric. I will provide a quick English only solution, if you need a multi-locale solution just change the implementation adding try/catch for Integer.parseInt(), Float.parseFloat() and so on.

  1. Create your utility method
    package com.nestorurquiza.utils;
    
    
    public final class StringUtils {
        
        private StringUtils(){}
        
        public static boolean isNumeric(String value) {
            if(value == null) {
                return false;
            } else {
                return (value.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+"));
            }
        }
    
    }
    
  2. Create file /WEB-INF/tld/StringUtils.tld
    <?xml version="1.0" encoding="UTF-8"?>
    <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemalocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
        <tlib-version>2.1</tlib-version>
        <uri>StringUtils</uri>
        
        <function>
            <name>isNumeric</name>
            <function-class>com.nestorurquiza.utils.StringUtils</function-class>
            <function-signature>
                boolean isNumeric( java.lang.String )
            </function-signature>
        </function>
    </taglib>
    
  3. Include a directive in your JSP to declare the prefix to use with the taglib
    <%@ taglib prefix="su" uri="/WEB-INF/tld/StringUtils.tld"%>
    
  4. Use the function in JSP
    <c:choose>
        <c:when test="${su:isNumeric('44.4')}">
            Is a number
        </c:when>
        <c:otherwise>
            Is not a number
        </c:otherwise>
    </c:choose>
    

No comments:

Followers