我知道丑陋的方式
a>0 ? a : -a但是当a是一个相对较长的表达式时,这很烦人.
but this is very annoyng when a is a relatively long expression.
OBJ1["x"]-someVar>0 ? OBJ1["x"]-someVar : -(OBJ1["x"]-someVar)还有更好的方法吗?
推荐答案对于纯jsp,您可以创建一个自定义的EL函数,该函数委托给 Math#abs(int) .
For plain jsp, you can create a custom EL function which delegates to Math#abs(int).
如果您只是先创建一个/WEB-INF/functions.tld文件,如下所示:
If you first just create a /WEB-INF/functions.tld file which look like follows:
<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="java.sun/xml/ns/javaee" xmlns:xsi="www.w3/2001/XMLSchema-instance" xsi:schemaLocation="java.sun/xml/ns/javaee java.sun/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>Custom_Functions</short-name> <uri>example/functions</uri> <function> <name>abs</name> <function-class>java.lang.Math</function-class> <function-signature>int abs(int)</function-signature> </function> </taglib>然后您将可以按以下方式使用它:
Then you'll be able to use it as follows:
<%@taglib uri="example/functions" prefix="f" %> ... ${f:abs(OBJ1["x"]-someVar)}该解决方案也适用于JSF,但是如果您使用的是JSF, OmniFaces 通过提供以下内容为您简化了此操作:其 importFunctions (如果尚未将OmniFaces与JSF一起使用,则应该开始使用它)
This solution also works for JSF, but if you are using JSF, OmniFaces has simplified this for you by providing its importFunctions (if not already using OmniFaces with JSF, you should start using it)
<o:importFunctions type="java.lang.Math" var="m" /> ... #{m:abs(-10)}另请参见:
- 我们的EL Wiki页面
- Our EL wiki page
See also:
更多推荐
EL有什么功能可以获取数字的绝对值?
发布评论