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.
- 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]+)?)+")); } } }
- 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>
- Include a directive in your JSP to declare the prefix to use with the taglib
<%@ taglib prefix="su" uri="/WEB-INF/tld/StringUtils.tld"%>
- 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:
Post a Comment