EL 任何函数来获得一个数字的绝对值? [英] EL any function to get absolute value of a number?

查看:31
本文介绍了EL 任何函数来获得一个数字的绝对值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道丑陋的方式

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="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>Custom_Functions</short-name>
    <uri>http://example.com/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="http://example.com/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 维基页面
  • 这篇关于EL 任何函数来获得一个数字的绝对值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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