I am experimenting with
Tomcat 5.0.12/Java 1.4.2_12. The exercise was to generate multiple unique random "lucky numbers." Using a bean everything worked fine. I get unique random numbers from the bean, but not from the custom tag. It is simple code - here is the bean code:
package com.lwk;
import java.util.*;
public class LuckyNumberBean implements java.io.Serializable {
private Random rnd = new Random();
public LuckyNumberBean() {}
public int getLuckyNumber() {
return rnd.nextInt(99);
}
}
My
JSP that calls it looks like this (
test case to generate just two random numbers):
<html>
<head>
<title>Gimme Some Lucky Lotto Numbers</title>
</head>
<body bgcolor="white">
<h1>Your Lucky Numbers Are:</h1>
<jsp:useBean id="lucky" class="com.lwk.LuckyNumberBean" />
<p>${lucky.luckyNumber} - ${lucky.luckyNumber}</p>
</body>
</html>
Again, simple stuff and works as expected. Generates two unique random numbers above for each ${lucky.luckyNumber} EL. What was not expected was when I tried it in a custom tag library. The
Java code looks like this:
package com.lwk;
import java.util.*;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class LuckyNumberTag extends SimpleTagSupport {
private Random rnd = new Random();
public void doTag() throws IOException {
JspWriter out = getJspContext().getOut();
out.println(rnd.nextInt(99));
}
}
And here is the JSP that calls it:
<%@ page contentType="text/html" %>
<%@ taglib prefix="lwk" uri="lwktaglib" %>
<html>
<head>
<title>2 Lucky Numbers</title>
</head>
<body bgcolor="white">
<h1>Your Lucky Numbers Are:</h1>
<p><lwk:getLuckyNumber /> - <lwk:getLuckyNumber /></p>
</body>
</html>
What is odd is that both "Lucky Numbers" generated above from the custom tag <lwk:getLuckyNumber /> are _always_ the same number (in the real code was getting 36 numbers - again, all the same).
No problem really I guess - just use the bean, but just don't quite understand why the custom tag doesn't work the same.
Thanks for your insights,
Lawrence Kennon