tags:

views:

542

answers:

3

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>

Thanks in advanced

+3  A: 

Hope it helps! random taglib

Also you may try $Math.random function.

Yeti
+4  A: 

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

BalusC
If there's always going to be just two values, I'd go for a nextBoolean ;)
Photodeus
+1  A: 

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.

rmarimon