随机数字 浮点数 字符串产生

JSP中经常用到随机数字或字符(如密码产生 sessionid产生)可以使用taglib标签产生,本人使用bean产生随机数:


1.可以产生10000000 和 99999999之间随机数

2.可以产生规定数字之间的随机数,如25 100之间

3.可以使用algorithm 和 provider产生一个SecureRandom随机数字或字符串
object instead of a Random object: 71 

4.可以产生浮点浮点随机数;

5.可以产生a-zA-Z0-9之间的规定长度个字符串

6.可以产生规定长度的小写字母字符串

7.可以产生任意字符串.


以下jsp bean 在Tomcat Win2000 下调试通过:
  1/*
  2*
  3* 随机数字bean
  4*/
 
  5
  6package mycollect;
  7
  8import java.util.*;
  9import java.security.SecureRandom;
 10import java.security.NoSuchAlgorithmException;
 11import java.security.NoSuchProviderException;
 12
 13
 14public class RandomNum {
 15
 16private Long randomnum = null;
 17private Float randomfloat = null;
 18private boolean floatvalue = false;
 19private long upper = 100;
 20private long lower = 0;
 21private String algorithm = null;
 22private String provider = null;
 23private boolean secure = false;
 24private Random random = null;
 25private SecureRandom secrandom = null;
 26
 27private final float getFloat() {
 28if (random == null)
 29return secrandom.nextFloat();
 30else
 31return random.nextFloat();
 32}

 33
 34public final void generateRandomObject() throws Exception {
 35
 36// check to see if the object is a SecureRandom object
 37if (secure) {
 38try {
 39// get an instance of a SecureRandom object
 40if (provider != null)
 41// search for algorithm in package provider
 42secrandom = SecureRandom.getInstance(algorithm, provider);
 43else
 44secrandom = SecureRandom.getInstance(algorithm);
 45}
 catch (NoSuchAlgorithmException ne) {
 46throw new Exception(ne.getMessage());
 47}
 catch (NoSuchProviderException pe) {
 48throw new Exception(pe.getMessage());
 49}

 50}
 else
 51random = new Random();
 52}

 53
 54/**
 55* generate the random number
 56*
 57*/

 58private final void generaterandom() {
 59
 60int tmprandom = 0// temp storage for random generated number
 61Integer rand;
 62
 63// check to see if float value is expected
 64if (floatvalue)
 65randomfloat = new Float(getFloat());
 66else
 67randomnum = new Long(lower + (long) ((getFloat() * (upper - lower))));
 68}

 69
 70public final Number getRandom() {
 71generaterandom(); 
 72if (floatvalue)
 73return randomfloat;
 74else
 75return randomnum;
 76}

 77
 78public final void setRange(long low, long up) {
 79
 80// set the upper and lower bound of the range
 81lower = low;
 82upper = up;
 83
 84// check to see if a float value is expected
 85if ((lower == 0&& (upper == 1))
 86floatvalue = true;
 87}

 88
 89/**
 90* set the algorithm name
 91*
 92@param value name of the algorithm to use for a SecureRandom object
 93*
 94*/

 95public final void setAlgorithm(String value) {
 96algorithm = value;
 97secure = true// a SecureRandom object is to be used
 98}

 99
100public final void setProvider(String value) 
101{
102provider = value;
103}

104
105public final void setRange(String value) throws Exception 
106{
107try 
108{
109upper = new Integer(value.substring(value.indexOf('-'+ 1)).longValue();
110}
 catch (Exception ex) {
111throw new Exception("upper attribute could not be" +
112" turned into an Integer default value was used"); 
113}

114
115try 
116{
117lower = new Integer(value.substring(0, value.indexOf('-'))).longValue();
118}
 catch (Exception ex) {
119throw new Exception("lower attribute could not be" +
120" turned into an Integer default value was used"); 
121}

122
123if ((lower == 0&& (upper == 1))
124floatvalue = true;
125
126if (upper < lower)
127throw new Exception("You can't have a range where the lowerbound" +
128" is higher than the upperbound.");
129
130}

131
132
133}

134
随机字符串bean
  1package mycollect; 
  2
  3import java.util.*;
  4import java.security.SecureRandom;
  5import java.security.NoSuchAlgorithmException;
  6import java.security.NoSuchProviderException;
  7
  8public class RandomStrg {
  9
 10private String randomstr;
 11private boolean allchars = false;
 12//欠缺是8位字符串 
 13private Integer length = new Integer(8);
 14private HashMap hmap;
 15private ArrayList lower = null;
 16private ArrayList upper = null;
 17private char[] single = null;
 18private int singlecount = 0;
 19private boolean singles = false;
 20private String algorithm = null;
 21private String provider = null;
 22private boolean secure = false;
 23private Random random = null;
 24private SecureRandom secrandom = null;
 25
 26private final float getFloat() {
 27if (random == null)
 28return secrandom.nextFloat();
 29else
 30return random.nextFloat();
 31}

 32
 33/**
 34* generate the Random object that will be used for this random number 
 35* generator
 36*
 37*/

 38public final void generateRandomObject() throws Exception {
 39
 40// check to see if the object is a SecureRandom object
 41if (secure) {
 42try {
 43// get an instance of a SecureRandom object
 44if (provider != null)
 45// search for algorithm in package provider
 46random = SecureRandom.getInstance(algorithm, provider);
 47else
 48random = SecureRandom.getInstance(algorithm);
 49}
 catch (NoSuchAlgorithmException ne) {
 50throw new Exception(ne.getMessage());
 51}
 catch (NoSuchProviderException pe) {
 52throw new Exception(pe.getMessage());
 53}

 54}
 else
 55random = new Random();
 56}

 57
 58/**
 59* generate the random string
 60*
 61*/

 62private final void generaterandom() {
 63
 64if (allchars)
 65for (int i = 0; i < length.intValue(); i++)
 66randomstr = randomstr + new Character((char)((int34 + 
 67((int)(getFloat() * 93)))).toString();
 68else if (singles) {
 69// check if there are single chars to be included
 70
 71if (upper.size() == 3{
 72// check for the number of ranges max 3 uppercase lowercase digits
 73
 74// build the random string
 75for (int i = 0; i < length.intValue(); i++{
 76// you have four groups to choose a random number from, to make
 77// the choice a little more random select a number out of 100
 78
 79// get a random number even or odd
 80if (((int) (getFloat() * 100)) % 2 == 0{
 81
 82// the number was even get another number even or odd
 83if (((int) (getFloat() * 100)) % 2 == 0)
 84// choose a random char from the single char group
 85randomstr = randomstr + randomSingle().toString();
 86else
 87// get a random char from the first range
 88randomstr = randomstr + randomChar((Character)lower.get(2),
 89(Character)upper.get(2)).toString();
 90}
 else {
 91// the number was odd
 92
 93if (((int) (getFloat() * 100)) % 2 == 0)
 94// choose a random char from the second range
 95randomstr = randomstr + randomChar((Character)lower.get(1),
 96(Character)upper.get(1)).toString();
 97else
 98// choose a random char from the third range
 99randomstr = randomstr + randomChar((Character)lower.get(0), 
100(Character)upper.get(0)).toString();
101}

102}

103}
 else if (upper.size() == 2{
104// single chars are to be included choose a random char from
105// two different ranges
106
107// build the random char from single chars and two ranges
108for (int i = 0; i < length.intValue(); i++{
109// select the single chars or a range to get each random char
110// from
111
112if (((int)(getFloat() * 100)) % 2 == 0{
113
114// get random char from the single chars
115randomstr = randomstr + randomSingle().toString();
116}
 else if (((int) (getFloat() * 100)) % 2 == 0{
117
118// get the random char from the first range
119randomstr = randomstr + randomChar((Character)lower.get(1),
120(Character)upper.get(1)).toString();
121}
 else {
122
123// get the random char from the second range
124randomstr = randomstr + randomChar((Character)lower.get(0),
125(Character)upper.get(0)).toString();
126}

127}

128}
 else if (upper.size() == 1{
129
130// build the random string from single chars and one range
131for (int i = 0; i < length.intValue(); i++{
132if (((int) getFloat() * 100% 2 == 0)
133// get a random single char
134randomstr = randomstr + randomSingle().toString();
135else
136// get a random char from the range
137randomstr = randomstr + randomChar((Character)lower.get(0),
138(Character)upper.get(0)).toString();
139}

140}
 else {
141// build the rand string from single chars
142for (int i = 0; i < length.intValue(); i++)
143randomstr = randomstr + randomSingle().toString();
144}

145}
 else {
146
147// no single chars are to be included in the random string
148if (upper.size() == 3{
149
150// build random strng from three ranges
151for (int i = 0; i < length.intValue(); i++{
152
153if (((int) (getFloat() * 100)) % 2 == 0{
154
155// get random char from first range
156randomstr = randomstr + randomChar((Character)lower.get(2),
157(Character)upper.get(2)).toString();
158}
 else if (((int) (getFloat() * 100)) % 2 == 0{
159
160// get random char form second range
161randomstr = randomstr + randomChar((Character)lower.get(1),
162(Character)upper.get(1)).toString();
163}
 else {
164
165// get random char from third range
166randomstr = randomstr + randomChar((Character)lower.get(0),
167(Character)upper.get(0)).toString();
168}

169}

170}
 else if (upper.size() == 2{
171
172// build random string from two ranges
173for (int i = 0; i < length.intValue(); i++{
174if (((int) (getFloat() * 100)) % 2 == 0)
175// get random char from first range
176randomstr = randomstr + randomChar((Character)lower.get(1),
177(Character)upper.get(1)).toString();
178else
179// get random char from second range
180randomstr = randomstr + randomChar((Character)lower.get(0),
181(Character)upper.get(0)).toString();
182}

183}
 else
184
185// build random string
186for (int i = 0; i < length.intValue(); i++)
187// get random char from only range
188randomstr = randomstr + randomChar((Character)lower.get(0), 
189(Character)upper.get(0)).toString();
190}

191}

192
193/**
194* generate a random char from the single char list
195*
196* @returns - a randomly selscted character from the single char list
197*
198*/

199private final Character randomSingle() {
200
201return (new Character(single[(int)((getFloat() * singlecount) - 1)]));
202}

203
204/**
205* generate a random character
206*
207@param lower lower bound from which to get a random char
208@param upper upper bound from which to get a random char
209*
210* @returns - a randomly generated character
211*
212*/

213private final Character randomChar(Character lower, Character upper) {
214int tempval;
215char low = lower.charValue();
216char up = upper.charValue();
217
218// get a random number in the range lowlow - lowup
219tempval = (int)((int)low + (getFloat() * ((int)(up - low))));
220
221// return the random char
222return (new Character((char) tempval));
223}

224
225/**
226* get the randomly created string for use with the 
227* <jsp:getProperty name=<i>"id"</i> property="randomstr"/>
228*
229@return - randomly created string
230*
231*/

232public final String getRandom() {
233
234randomstr = new String();
235
236generaterandom(); // generate the first random string
237
238if (hmap != null{
239
240while (hmap.containsKey(randomstr)) {
241// random string has already been created generate a different one
242generaterandom();
243}

244
245hmap.put(randomstr, null); // add the new random string
246}

247
248return randomstr;
249}

250
251/**
252* set the ranges from which to choose the characters for the random string
253*
254@param low set of lower ranges
255@param up set of upper ranges
256*
257*/

258public final void setRanges(ArrayList low, ArrayList up) {
259lower = low;
260upper = up;
261}

262
263
264/**
265* set the hashmap that is used to check the uniqueness of random strings
266*
267@param map hashmap whose keys are used to insure uniqueness of random strgs
268*
269*/

270public final void setHmap(HashMap map) {
271hmap = map;
272}

273
274/**
275* set the length of the random string
276*
277@param value length of the random string
278*
279*/

280public final void setLength(String value) {
281length = new Integer(value);
282
283}

284
285/**
286* set the algorithm name
287*
288@param value name of the algorithm to use for a SecureRandom object
289*
290*/

291public final void setAlgorithm(String value) {
292algorithm = value;
293secure = true// a SecureRandom object is to be used
294}

295
296/**
297* set the provider name
298*
299@param value name of the package to check for the algorithm
300*
301*/

302public final void setProvider(String value) {
303provider = value;
304}

305
306/**
307* set the allchars flag
308*
309@param value boolean value of the allchars flag
310*
311*/

312public final void setAllchars(boolean value) {
313allchars = value;
314}

315
316/**
317* set the array of single chars to choose from for this random string and the
318* number of chars in the array
319*
320@param chars the array of single chars
321@param value the number of single chars
322*
323*/

324public final void setSingle(char[] chars, int value) {
325single = chars; // set the array of chars
326singlecount = value; // set the number of chars in array single
327singles = true// set flag that single chars are in use
328}

329
330public final void setCharset(String value) 
331{
332// values tells the method whether or not to check for single chars
333boolean more = true;
334
335// create the arraylists to hold the upper and lower bounds for the char
336// ranges
337lower = new ArrayList(3);
338upper = new ArrayList(3);
339
340// user has chosen to use all possible characters in the random string
341if (value.compareTo("all"== 0{
342allchars = true// set allchars flag
343// all chars are to be used so there are no single chars to sort 
344// through
345more = false;
346}
else if ((value.charAt(1== '-'&& (value.charAt(0!= '\\')) {
347// run through the ranges at most 3 
348while (more && (value.charAt(1== '-')){
349
350// check to make sure that the dash is not the single char
351if (value.charAt(0== '\\')
352break;
353else {
354// add upper and lower ranges to there list
355lower.add(new Character(value.charAt(0)));
356upper.add(new Character(value.charAt(2)));
357}

358
359// check to see if there is more to the charset
360if (value.length() <= 3)
361more = false;
362else
363// create a new string so that the next range if there is one
364// starts it
365value = value.substring(3);
366}

367}

368
369// if more = false there are no single chars in the charset
370if (more) {
371
372single = new char[30]; // create single
373
374// create a set of tokens from the string of single chars
375StringTokenizer tokens = new StringTokenizer(value);
376
377while (tokens.hasMoreTokens()) {
378// get the next token from the string
379String token = tokens.nextToken();
380
381if (token.length() > 1)
382// char is a - add it to the list
383single[singlecount++= '-';
384
385// add the current char to the list
386single[singlecount++= token.charAt(0);
387}

388}

389if ((lower == null&& (single == null))
390setCharset("a-zA-Z0-9"); 
391}

392}

393
JSP调用语句:
 1<%@ page contentType="text/html;charset=ISO8859_1" %> 
 2<%@ page import="java.util.*" %> 
 3<jsp:useBean id="RNUM" scope="page" class="mycollect.RandomNum" />
 4<jsp:useBean id="RSTR" scope="page" class="mycollect.RandomStrg" />
 5
 6<html>
 7<head>
 8<title>随机数字 浮点数 字符串</title>
 9<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
10</head>
11
12<body>
13<h3>随机数字 浮点数 字符串</h3>
14<%
15//Random generator = new Random();
16//int limit = 10;
17//int randomNumber = (int)(generator.nextDouble() * limit);
18
19
20out.println("<p>创建在10000000 和 99999999之间的随机数:");
21RNUM.setRange("10000000-99999999");
22RNUM.generateRandomObject();
23out.println("<b>"+RNUM.getRandom().intValue()+"</b>");
24
25out.println("<p>在n 25 和 100之间创建一个随机数:");
26RNUM.setRange("25-100");
27RNUM.generateRandomObject();
28out.println("<b>"+RNUM.getRandom().intValue()+"</b>");
29
30%>
31<p>Create the same random number between 25 and 100, only use the <br>
32algorithm and provider attributes to indicate the use of a SecureRandom<br>
33object instead of a Random object:
34<% 
35RNUM.setRange("25-100");
36RNUM.setAlgorithm("SHA1PRNG");
37RNUM.setProvider("SUN");
38RNUM.generateRandomObject();
39out.println("<b>"+RNUM.getRandom().intValue()+"</b>");
40
41out.println("<p>Create a random float value:");
42RNUM.setRange("0-1");
43RNUM.generateRandomObject();
44String radio= new java.text.DecimalFormat("###.##########").format(RNUM.getRandom());
45out.println("<b>"+radio+"</b>");
46
47out.println("<p>===========================================");
48
49out.println("<p>在a-zA-Z0-9之间,也就是数字和26个字母混合的随机字符串,(欠缺是8位,该功能适合创建随机密码和sessionid)");
50RSTR.setCharset("a-zA-Z0-9");
51RSTR.generateRandomObject();
52out.println("<b>"+RSTR.getRandom()+"</b>");
53
54
55out.println("<p>Create a random string 15 lowercase letters long:");
56RSTR.setCharset("a-z");
57RSTR.setLength("15");
58RSTR.generateRandomObject();
59out.println("<b>"+RSTR.getRandom()+"</b>");
60
61out.println("<p>Create a random string with only caps:");
62RSTR.setCharset("A-Z");
63RSTR.generateRandomObject();
64out.println("<b>"+RSTR.getRandom()+"</b>");
65
66out.println("<p>Create a random string 10 characters long with the charset a-fF-K ! \\ $ % # ^ - * ? notice that the - and had to be escaped with a :");
67RSTR.setCharset("a-fF-K!\\$%#^-*?");
68RSTR.setLength("10");
69RSTR.generateRandomObject();
70out.println("<b>"+RSTR.getRandom()+"</b>");
71
72
73out.println("<p>Create a random string of all the characters and digits:");
74RSTR.setCharset("all");
75RSTR.generateRandomObject();
76out.println("<b>"+RSTR.getRandom()+" </b>");
77
78%><p>
79Create the same random string of all the characters and digits, only use<br>
80the algorithm and provider attributes to indicate the use of a SecureRandom<br>
81object instead of a Random object:
82<%
83RSTR.setCharset("all");
84RSTR.setAlgorithm("SHA1PRNG");
85RSTR.setProvider("SUN");
86RSTR.generateRandomObject();
87out.println("<b>"+RSTR.getRandom()+"</b>");
88
89%>
90
91</body>
92</html>
93
原文地址:https://www.cnblogs.com/QDuck/p/415158.html