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="" xmlns:xsi=""
                boolean isNumeric( java.lang.String )
  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:when test="${su:isNumeric('44.4')}">
            Is a number
            Is not a number

No comments: