| |
| 随机数字 浮点数 字符串产生 |
| |
发布者: 发布时间:2006-07-04 |
|
|
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 下调试通过:
/* * * 随机数字bean */
package mycollect;
import java.util.*; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException;
public class RandomNum {
private Long randomnum = null; private Float randomfloat = null; private boolean floatvalue = false; private long upper = 100; private long lower = 0; private String algorithm = null; private String provider = null; private boolean secure = false; private Random random = null; private SecureRandom secrandom = null;
private final float getFloat() { if (random == null) return secrandom.nextFloat(); else return random.nextFloat(); }
public final void generateRandomObject() throws Exception {
// check to see if the object is a SecureRandom object if (secure) { try { // get an instance of a SecureRandom object if (provider != null) // search for algorithm in package provider secrandom = SecureRandom.getInstance(algorithm, provider); else secrandom = SecureRandom.getInstance(algorithm); } catch (NoSuchAlgorithmException ne) { throw new Exception(ne.getMessage()); } catch (NoSuchProviderException pe) { throw new Exception(pe.getMessage()); } } else random = new Random(); }
/** * generate the random number * */ private final void generaterandom() {
int tmprandom = 0; // temp storage for random generated number Integer rand;
// check to see if float value is expected if (floatvalue) randomfloat = new Float(getFloat()); else randomnum = new Long(lower + (long) ((getFloat() * (upper - lower)))); }
public final Number getRandom() { generaterandom(); if (floatvalue) return randomfloat; else return randomnum; }
public final void setRange(long low, long up) {
// set the upper and lower bound of the range lower = low; upper = up;
// check to see if a float value is expected if ((lower == 0) && (upper == 1)) floatvalue = true; }
/** * set the algorithm name * * @param value name of the algorithm to use for a SecureRandom object * */ public final void setAlgorithm(String value) { algorithm = value; secure = true; // a SecureRandom object is to be used }
public final void setProvider(String value) { provider = value; }
public final void setRange(String value) throws Exception { try { upper = new Integer(value.substring(value.indexOf('-') + 1)).longValue(); } catch (Exception ex) { throw new Exception("upper attribute could not be" + " turned into an Integer default value was used"); }
try { lower = new Integer(value.substring(0, value.indexOf('-'))).longValue(); } catch (Exception ex) { throw new Exception("lower attribute could not be" + " turned into an Integer default value was used"); }
if ((lower == 0) && (upper == 1)) floatvalue = true;
if (upper < lower) throw new Exception("You can't have a range where the lowerbound" + " is higher than the upperbound.");
}
}
| 随机字符串bean
package mycollect;
import java.util.*; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException;
public class RandomStrg {
private String randomstr; private boolean allchars = false; //欠缺是8位字符串 private Integer length = new Integer(8); private HashMap hmap; private ArrayList lower = null; private ArrayList upper = null; private char[] single = null; private int singlecount = 0; private boolean singles = false; private String algorithm = null; private String provider = null; private boolean secure = false; private Random random = null; private SecureRandom secrandom = null;
private final float getFloat() { if (random == null) return secrandom.nextFloat(); else return random.nextFloat(); }
/** * generate the Random object that will be used for this random number * generator * */ public final void generateRandomObject() throws Exception {
// check to see if the object is a SecureRandom object if (secure) { try { // get an instance of a SecureRandom object if (provider != null) // search for algorithm in package provider random = SecureRandom.getInstance(algorithm, provider); else random = SecureRandom.getInstance(algorithm); } catch (NoSuchAlgorithmException ne) { throw new Exception(ne.getMessage()); } catch (NoSuchProviderException pe) { throw new Exception(pe.getMessage()); } } else random = new Random(); }
/** * generate the random string * */ private final void generaterandom() {
if (allchars) for (int i = 0; i < length.intValue(); i++) randomstr = randomstr + new Character((char)((int) 34 + ((int)(getFloat() * 93)))).toString(); else if (singles) { // check if there are single chars to be included
if (upper.size() == 3) { // check for the number of ranges max 3 uppercase lowercase digits
// build the random string for (int i = 0; i < length.intValue(); i++) { // you have four groups to choose a random number from, to make // the choice a little more random select a number out of 100
// get a random number even or odd if (((int) (getFloat() * 100)) % 2 == 0) {
// the number was even get another number even or odd if (((int) (getFloat() * 100)) % 2 == 0) // choose a random char from the single char group randomstr = randomstr + randomSingle().toString(); else // get a random char from the first range randomstr = randomstr + randomChar((Character)lower.get(2), (Character)upper.get(2)).toString(); } else { // the number was odd
if (((int) (getFloat() * 100)) % 2 == 0) // choose a random char from the second range randomstr = randomstr + randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); else // choose a random char from the third range randomstr = randomstr + randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } } else if (upper.size() == 2) { // single chars are to be included choose a random char from // two different ranges
// build the random char from single chars and two ranges for (int i = 0; i < length.intValue(); i++) { // select the single chars or a range to get each random char // from
if (((int)(getFloat() * 100)) % 2 == 0) {
// get random char from the single chars randomstr = randomstr + randomSingle().toString(); } else if (((int) (getFloat() * 100)) % 2 == 0) {
// get the random char from the first range randomstr = randomstr + randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); } else {
// get the random char from the second range randomstr = randomstr + randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } } else if (upper.size() == 1) {
// build the random string from single chars and one range for (int i = 0; i < length.intValue(); i++) { if (((int) getFloat() * 100) % 2 == 0) // get a random single char randomstr = randomstr + randomSingle().toString(); else // get a random char from the range randomstr = randomstr + randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } else { // build the rand string from single chars for (int i = 0; i < length.intValue(); i++) randomstr = randomstr + randomSingle().toString(); } } else {
// no single chars are to be included in the random string if (upper.size() == 3) {
// build random strng from three ranges for (int i = 0; i < length.intValue(); i++) {
if (((int) (getFloat() * 100)) % 2 == 0) {
// get random char from first range randomstr = randomstr + randomChar((Character)lower.get(2), (Character)upper.get(2)).toString(); } else if (((int) (getFloat() * 100)) % 2 == 0) {
// get random char form second range randomstr = randomstr + randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); } else {
// get random char from third range randomstr = randomstr + randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } } else if (upper.size() == 2) {
// build random string from two ranges for (int i = 0; i < length.intValue(); i++) { if (((int) (getFloat() * 100)) % 2 == 0) // get random char from first range randomstr = randomstr + randomChar((Character)lower.get(1), (Character)upper.get(1)).toString(); else // get random char from second range randomstr = randomstr + randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } } else
// build random string for (int i = 0; i < length.intValue(); i++) // get random char from only range randomstr = randomstr + randomChar((Character)lower.get(0), (Character)upper.get(0)).toString(); } }
/** * generate a random char from the single char list * * @returns - a randomly selscted character from the single char list * */ private final Character randomSingle() {
return (new Character(single[(int)((getFloat() * singlecount) - 1)])); }
/** * generate a random character * * @param lower lower bound from which to get a random char * @param upper upper bound from which to get a random char * * @returns - a randomly generated character * */ private final Character randomChar(Character lower, Character upper) { int tempval; char low = lower.charValue(); char up = upper.charValue();
// get a random number in the range lowlow - lowup tempval = (int)((int)low + (getFloat() * ((int)(up - low))));
// return the random char return (new Character((char) tempval)); }
/** * get the randomly created string for use with the * <jsp:getProperty name=<i>"id"</i> property="randomstr"/> * * @return - randomly created string * */ public final String getRandom() {
randomstr = new String();
generaterandom(); // generate the first random string
if (hmap != null) {
while (hmap.containsKey(randomstr)) { // random string has already been created generate a different one generaterandom(); }
hmap.put(randomstr, null); // add the new random string }
return randomstr; }
/** * set the ranges from which to choose the characters for the random string * * @param low set of lower ranges * @param up set of upper ranges * */ public final void setRanges(ArrayList low, ArrayList up) { lower = low; upper = up; }
/** * set the hashmap that is used to check the uniqueness of random strings * * @param map hashmap whose keys are used to insure uniqueness of random strgs * */ public final void setHmap(HashMap map) { hmap = map; }
/** * set the length of the random string * * @param value length of the random string * */ public final void setLength(String value) { length = new Integer(value);
}
/** * set the algorithm name * * @param value name of the algorithm to use for a SecureRandom object * */ public final void setAlgorithm(String value) { algorithm = value; secure = true; // a SecureRandom object is to be used }
/** * set the provider name * * @param value name of the package to check for the algorithm * */ public final void setProvider(String value) { provider = value; }
/** * set the allchars flag * * @param value boolean value of the allchars flag * */ public final void setAllchars(boolean value) { allchars = value; }
/** * set the array of single chars to choose from for this random string and the * number of chars in the array * * @param chars the array of single chars * @param value the number of single chars * */ public final void setSingle(char[] chars, int value) { single = chars; // set the array of chars singlecount = value; // set the number of chars in array single singles = true; // set flag that single chars are in use }
public final void setCharset(String value) { // values tells the method whether or not to check for single chars boolean more = true;
// create the arraylists to hold the upper and lower bounds for the char // ranges lower = new ArrayList(3); upper = new ArrayList(3);
// user has chosen to use all possible characters in the random string if (value.compareTo("all") == 0) { allchars = true; // set allchars flag // all chars are to be used so there are no single chars to sort // through more = false; }else if ((value.charAt(1) == '-') && (value.charAt(0) != '\\')) { // run through the ranges at most 3 while (more && (value.charAt(1) == '-')){
// check to make sure that the dash is not the single char if (value.charAt(0) == '\\') break; else { // add upper and lower ranges to there list lower.add(new Character(value.charAt(0))); upper.add(new Character(value.charAt(2))); }
// check to see if there is more to the charset if (value.length() <= 3) more = false; else // create a new string so that the next range if there is one // starts it value = value.substring(3); } }
// if more = false there are no single chars in the charset if (more) {
single = new char[30]; // create single
// create a set of tokens from the string of single chars StringTokenizer tokens = new StringTokenizer(value);
while (tokens.hasMoreTokens()) { // get the next token from the string String token = tokens.nextToken();
if (token.length() > 1) // char is a - add it to the list single[singlecount++] = '-';
// add the current char to the list single[singlecount++] = token.charAt(0); } } if ((lower == null) && (single == null)) setCharset("a-zA-Z0-9"); } }
| JSP调用语句:
<%@ page contentType="text/html;charset=ISO8859_1" %> <%@ page import="java.util.*" %> <jsp:useBean id="RNUM" scope="page" class="mycollect.RandomNum" /> <jsp:useBean id="RSTR" scope="page" class="mycollect.RandomStrg" />
<html> <head> <title>随机数字 浮点数 字符串</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head>
<body> <h3>随机数字 浮点数 字符串</h3> <% //Random generator = new Random(); //int limit = 10; //int randomNumber = (int)(generator.nextDouble() * limit);
out.println("<p>创建在10000000 和 99999999之间的随机数:"); RNUM.setRange("10000000-99999999"); RNUM.generateRandomObject(); out.println("<b>"+RNUM.getRandom().intValue()+"</b>");
out.println("<p>在n 25 和 100之间创建一个随机数:"); RNUM.setRange("25-100"); RNUM.generateRandomObject(); out.println("<b>"+RNUM.getRandom().intValue()+"</b>");
%> <p>Create the same random number between 25 and 100, only use the <br> algorithm and provider attributes to indicate the use of a SecureRandom<br> object instead of a Random object: <% RNUM.setRange("25-100"); RNUM.setAlgorithm("SHA1PRNG"); RNUM.setProvider("SUN"); RNUM.generateRandomObject(); out.println("<b>"+RNUM.getRandom().intValue()+"</b>");
out.println("<p>Create a random float value:"); RNUM.setRange("0-1"); RNUM.generateRandomObject(); String radio= new java.text.DecimalFormat("###.##########").format(RNUM.getRandom()); out.println("<b>"+radio+"</b>");
out.println("<p>===========================================");
out.println("<p>在a-zA-Z0-9之间,也就是数字和26个字母混合的随机字符串,(欠缺是8位,该功能适合创建随机密码和sessionid)"); RSTR.setCharset("a-zA-Z0-9"); RSTR.generateRandomObject(); out.println("<b>"+RSTR.getRandom()+"</b>");
out.println("<p>Create a random string 15 lowercase letters long:"); RSTR.setCharset("a-z"); RSTR.setLength("15"); RSTR.generateRandomObject(); out.println("<b>"+RSTR.getRandom()+"</b>");
out.println("<p>Create a random string with only caps:"); RSTR.setCharset("A-Z"); RSTR.generateRandomObject(); out.println("<b>"+RSTR.getRandom()+"</b>");
out.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 :"); RSTR.setCharset("a-fF-K!\\$%#^-*?"); RSTR.setLength("10"); RSTR.generateRandomObject(); out.println("<b>"+RSTR.getRandom()+"</b>");
out.println("<p>Create a random string of all the characters and digits:"); RSTR.setCharset("all"); RSTR.generateRandomObject(); out.println("<b>"+RSTR.getRandom()+" </b>");
%><p> Create the same random string of all the characters and digits, only use<br> the algorithm and provider attributes to indicate the use of a SecureRandom<br> object instead of a Random object: <% RSTR.setCharset("all"); RSTR.setAlgorithm("SHA1PRNG"); RSTR.setProvider("SUN"); RSTR.generateRandomObject(); out.println("<b>"+RSTR.getRandom()+"</b>");
%>
</body> </html>
|
|
| (转载文章请保留出处:北天JAVA技术网(www.java114.com)) |
| |
| 更多精彩文章: |
| 创建JSP站点 |
| JSP中日期的用法 |
| 轻松使用JSP生成饼图 |
| Java实时应用程序中的内存管理 |
| 第一个Servlet |
| 在网页上发布统计曲线(统计图) |
| |
|
|
| |
| 免责声明:该文章由网友发表,如果对您造成侵权,请联系站长。 |
|