如何检查JSTL中的isNumeric/isNumber? [英] How to check isNumeric / isNumber in JSTL?

查看:74
本文介绍了如何检查JSTL中的isNumeric/isNumber?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JSTL中进行此简单检查(不扩展任何Java类和其他JSP函数).我需要这样:

How to do this simple check in JSTL (without extending any Java classes and additional JSP functions). I need it like this:

<c:if test="${fn:isNumeric()}">
    // do something
</c:if>

先谢谢了.

推荐答案

如果您的环境支持在EL对象上调用非getter方法的新EL 2.2功能(在所有与Servlet 3.0兼容的容器中都可用,例如Tomcat 7) ,Glassfish 3等),那么您可以只使用

If your environment supports the new EL 2.2 feature of invoking non-getter methods on EL objects (which is available in all Servlet 3.0 compatible containers, such as Tomcat 7, Glassfish 3, etc), then you could just use the String#matches() method directly in EL.

<c:set var="numberAsString">${someExpressionToTestForNumber}</c:set>
<c:if test="${numberAsString.matches('[0-9]+')}">
    It's a number!
</c:if>

(我将减号-以及千位和分数分隔符,.排除在可能的字符之外,这些字符可能会以技术上有效的数字出现)

(I'll leave the minus - and the thousands and fraction separators , and . outside consideration as possible characters which may appear in a technically valid number)

请注意,带有 body 表达式的<c:set>使用String#valueOf()隐式将任何类型转换为String.否则,对于非String类型的<c:if>中的matches()调用将失败.

Note that the <c:set> with the expression in its body implicitly converts any type to String using String#valueOf(). Otherwise the matches() call in <c:if> would fail for non-String types.

这篇关于如何检查JSTL中的isNumeric/isNumber?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆