TNT blog  
          日歷
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345
          統(tǒng)計(jì)
          • 隨筆 - 5
          • 文章 - 40
          • 評(píng)論 - 7
          • 引用 - 0

          導(dǎo)航

          常用鏈接

          留言簿(2)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          收藏夾

          home

          搜索

          •  

          最新隨筆

          最新評(píng)論

          閱讀排行榜

           

          JSP中經(jīng)常用到隨機(jī)數(shù)字或字符(如密碼產(chǎn)生 sessionid產(chǎn)生)可以使用taglib標(biāo)簽產(chǎn)生,本人使用bean產(chǎn)生隨機(jī)數(shù):

          1.可以產(chǎn)生10000000 和 99999999之間隨機(jī)數(shù)

          2.可以產(chǎn)生規(guī)定數(shù)字之間的隨機(jī)數(shù),如25 100之間

          3.可以使用algorithm 和 provider產(chǎn)生一個(gè)SecureRandom隨機(jī)數(shù)字或字符串
          object instead of a Random object: 71

          4.可以產(chǎn)生浮點(diǎn)浮點(diǎn)隨機(jī)數(shù);

          5.可以產(chǎn)生a-zA-Z0-9之間的規(guī)定長度個(gè)字符串

          6.可以產(chǎn)生規(guī)定長度的小寫字母字符串

          7.可以產(chǎn)生任意字符串.

          以下jsp bean 在Tomcat Win2000 下調(diào)試通過:

          /*
          *
          * 隨機(jī)數(shù)字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.");

          }

          }

          //隨機(jī)字符串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
          * &lt;jsp:getProperty name=<i>"id"</i> property="randomstr"/&gt;
          *
          * @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調(diào)用語句:

          <%@ 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>隨機(jī)數(shù)字 浮點(diǎn)數(shù) 字符串</title>
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
          </head>

          <body>
          <h3>隨機(jī)數(shù)字 浮點(diǎn)數(shù) 字符串</h3>
          <%
          //Random generator = new Random();
          //int limit = 10;
          //int randomNumber = (int)(generator.nextDouble() * limit);


          out.println("<p>創(chuàng)建在10000000 和 99999999之間的隨機(jī)數(shù):");
          RNUM.setRange("10000000-99999999");
          RNUM.generateRandomObject();
          out.println("<b>"+RNUM.getRandom().intValue()+"</b>");

          out.println("<p>在n 25 和 100之間創(chuàng)建一個(gè)隨機(jī)數(shù):");
          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之間,也就是數(shù)字和26個(gè)字母混合的隨機(jī)字符串,(欠缺是8位,該功能適合創(chuàng)建隨機(jī)密碼和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>

          posted on 2006-06-01 10:41 TNT 閱讀(243) 評(píng)論(0)  編輯  收藏 所屬分類: JAVA
           
          Copyright © TNT Powered by: 博客園 模板提供:滬江博客
          主站蜘蛛池模板: 尼木县| 马公市| 平舆县| 普兰县| 合江县| 望奎县| 东方市| 图木舒克市| 清河县| 安达市| 信丰县| 高淳县| 渝中区| 图木舒克市| 安阳市| 商水县| 盐亭县| 绵阳市| 中牟县| 临清市| 廊坊市| 盐津县| 汝州市| 家居| 凤山县| 湖南省| 太保市| 洛扎县| 天长市| 昌都县| 娄烦县| 吉首市| 专栏| 裕民县| 望谟县| 阿图什市| 盱眙县| 三穗县| 庆城县| 弥勒县| 吐鲁番市|