In this tutorial we are going to discuss about the rolling dice in JSP.
JSP rolling dice
In this tutorial we are going to discuss about the rolling dice in JSP.
In Dice games there is a possibility to get the random number when the dice are rolled. When they are thrown possibility of coming number may be between the specified number. In the example we will assume the number may vary from 1 to 6. In our example we will use the JSP.
Example :
An example is being given here will demonstrate you about how to find the dice number randomly when it is rolled. In this example I have created a TLD file named jspRollDice.tld where described the function name and its class then create a java file named RollingDiceExample.java where created a public static function named as same as it is defined in the TLD file (remember function must be static). In this function used the random() method of java.lang.Math class that returns the double value which would be the greater than or equal to 0.0 and less than 1.0. Then created a JSP file where used the method rollingDice() which is declared in the TLD file. When this method will be invoked it will first be searched into the jspRollDice.tld file and here the method will be looked up and then in the tld file it will be seen for the class of this method where it is defined and will looked up in RollingDiceExample.java file and here the function will be executed in actual and will return the value which will be forwarded to the JSP page via the tld file.
jspRollDice.tld
<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <function> <name>rollingDice</name> <function-class>devmanuals.RollingDiceExample</function-class> <function-signature>int rollingDice()</function-signature> </function> </taglib>
RollingDiceExample.java
package devmanuals; public class RollingDiceExample { public static int rollingDice() { int dice = (int)(Math.random()*6)+1; return dice; } }
jspRollingDiceExample.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="WEB-INF/jspRollDice.tld" prefix="rDice" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP Rolling Dice Example</title> </head> <body> Value of Dice1 = <c:out value="${rDice:rollingDice()}"/><br> Value of Dice2 = <c:out value="${rDice:rollingDice()}"/> </body> </html>
Output :
When you will execute the above JSP page you will get the output as follows :
How many times you will execute this page a value of Dice1 & Dice2 will be varied between 1 to 6.
[ 0 ] Comments