简体   繁体   中英

How can I create my own functions that I can call from Expression Language in jsp in a Java web app?

Well, the question is pretty clear.

There is a web-app I have and in the jsp file for example I want to roll a dice like this:

${rollDiceDude}

How can I do this?

Well, all you need to do is to have this method, it must be public and static:

public class DiceRoller {
    public static int rollDice() {
        return new Random().nextInt(6) + 1; // Let's assume this is a regular die, not a 18 faced FRP one.. 
    }
}

And you will need a .tld file in your WEB-INF folder, for example, myFunctions.tld:

<?xml version="1.0" encoding="utf-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
        version="2.0">

    <tlib-version>1.2</tlib-version>
    <short-name>MyFunctions</short-name>
    <uri>DiceFunctions</uri>

    <function>
        <name>rollIt</name>
        <function-class>com.tugay.julyten.DiceRoller</function-class>
        <function-signature>
            int rollDice()
        </function-signature>
    </function>

</taglib>

Now in the jsp file all you have to do is:

<%@ taglib prefix="dF" uri="DiceFunctions" %> <!--This is a JSP directive btw.. -->
${dF:rollIt()} <!-- You can even pass arguments... -->

Hope it helps, good day!

This is called an EL function...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM