驗證碼技術是網站開放過程中該保護網站安全的最基本環節,它可以防止非法人員利用註冊工具或登錄工具來攻擊網站(也就是常說的灌水),從而保護網站安全。
/javabean/src/com/wgh/random/RanDom.java:
package com.wgh.random;
public class RanDom {
private String checknum=""; //生成的驗證碼
private int number=0; //用戶輸入的位數
public RanDom(){}
public void setNumber(int number){
this.number=number;
}
public int getNumber(){
return this.number;
}
public void makeChecknum(){
String sourcenum="0123456789"; //定義獲取隨機數的源字符串
String siglenum=""; //保存獲取到的單個隨機數
String checknum=""; //獲取到的隨機數
int index=0; //獲取隨機數的位置
int i=0;
while(i<this.number){
index=((int)(Math.random()*100))%(sourcenum.length()-1); //隨機生成獲取隨機數的位置
siglenum=sourcenum.substring(index,index+1); //獲取單個隨機數
checknum+=siglenum; //連接獲取到的隨機數
i++;
}
this.checknum=checknum;
}
public String getChecknum(){
return this.checknum;
}
}
dorandomnum.jsp:
<%@ page contentType="text/html;charset=utf-8"%>
<jsp:useBean id="myrandom" class="com.wgh.random.RanDom"/>
<%
String strnum=request.getParameter("number");
if(strnum==null)
strnum="0";
int num=0;
try{
num=Integer.parseInt(strnum);
}catch(Exception e){num=0;}
myrandom.setNumber(num);
myrandom.makeChecknum();
%>
<html>
<head>
<title>隨機產生指定位數的驗證碼</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<center>
<table style="margin-top:200" width="250" border="1" cellpadding="0" cellspacing="0" bordercolor="black" bordercolorlight="black" bordercolordark="white">
<tr bgcolor="lightgrey" height="30">
<td align="center">生成的驗證碼</td>
</tr>
<tr height="50">
<td align="center">
驗證碼的位數:<%=myrandom.getNumber() %>
<br>
生成的驗證碼:<%=myrandom.getChecknum()%>
</td>
</tr>
</table>
<a href="index.jsp">[返回]</a>
</center>
</body>
</html>
index.jsp:
<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>隨機產生指定位數的驗證碼</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<center>
<form action="dorandomnum.jsp">
<table style="margin-top:200" width="300" border="1" cellpadding="0" cellspacing="0" bordercolor="black" bordercolorlight="black" bordercolordark="white">
<tr bgcolor="lightgrey" height="25">
<td align="center">隨機產生指定位數的驗證碼</td>
</tr>
<tr height="50">
<td align="center">
輸入驗證碼位數:
<input type="text" name="number">
<input type="submit" name="logon" value="生成">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>