How to get a random number in JSTL?
Asked Answered
P

4

13

I would like to get something like the next code generated in JSTL

<c:choose>
    <c:when test="${random number is even}">
        <div class="redlogo">
    </c:when>
    <c:otherwise>
        <div class="greenlogo">
    </c:otherwise>
</c:choose>
Painkiller answered 16/2, 2010 at 13:13 Comment(0)
E
17

This one is a bit ugly but it works...

<c:set var="rand"><%= java.lang.Math.round(java.lang.Math.random() * 2) %></c:set>

Later you can check for ${rand mod 2 == 0} and ${rand mod 2 == 1} to get your desired output.

Eriha answered 16/2, 2010 at 18:39 Comment(0)
M
12

You could wrap java.util.Random in a bean and make use of jsp:useBean.

package com.example;

import java.util.Random;

public class RandomBean {
    private static final Random RANDOM = new Random();

    public int getNextInt() {
        return RANDOM.nextInt();
    }
}

...so that you can use it in your JSP as follows:

<jsp:useBean id="random" class="com.example.RandomBean" scope="application" />

...

<div class="${random.nextInt % 2 == 0 ? 'redlogo' : 'greenlogo'}">

(note that I optimized the c:choose away with help of the ternary operator).

Mt answered 16/2, 2010 at 13:36 Comment(3)
If there's always going to be just two values, I'd go for a nextBoolean ;)Waterage
just a note - if EL supports calling methods, then you can skip the bean and use ${random.nextInt() ... } (+1 was given long ago :) )Split
@Split try you can understand. It need getter and setterLoki
A
12

I just want to point out, that if you are using EL 2.2 (or above), you can directly call any method in EL (see this question), so probably the quickest method is to initialize a bean

<jsp:useBean id="random" class="java.util.Random" scope="application" />

and then directly invoke nextInt() or any other method from java.util.Random inside page:

${random.nextInt()}

or with parameter:

${random.nextInt(10)}
Alphabetical answered 17/10, 2013 at 14:33 Comment(3)
EL would presume that java.util.Random has a method getNextInt(). Which it hasn't.Carthy
no, it wouldn't, because you will invoke it with brackets or with arguments in brackets. Read Invoking non-getter methods section in EL wiki pageAlphabetical
I know some time has passed, but this is a far better solution than the selected answer.Jesse
C
3

Hope it helps! random taglib

Also you may try $Math.random function.

Cioffi answered 16/2, 2010 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.