Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

jsp - EL any function to get absolute value of a number?

I know the ugly way

a>0 ? a : -a

but this is very annoyng when a is a relatively long expression.

OBJ1["x"]-someVar>0 ? OBJ1["x"]-someVar : -(OBJ1["x"]-someVar)

Is there any nicer way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For plain jsp, you can create a custom EL function which delegates to Math#abs(int).

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)}

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)}

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...