1、HTML
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function getValidCod()
{
document.getElementById("imgCode").src="ValidateCodeServlet?date='+new Date();";
}
</script>
</head>
<body onLoad="getValidCod();">
This is my JSP page.
<br>
<input name="validataCode" type="text"
style="width: 52px; height: 21px;">
<img id="imgCode" src="images/img/blank.gif"
onClick="javascript:this.src='ValidateCodeServlet?date='+new Date();"'
style="margin: 0px 2px -4px 0px; cursor: pointer" title="看不清,換一張?" />
</body>
</html>
2、web.xml
<!-- 登入驗證碼 -->
<servlet>
<servlet-name>ValidateCodeServlet</servlet-name>
<servlet-class>valdateCode.ValidateCodeServlet</servlet-class>
<init-param>
<param-name>width</param-name>
<param-value>70</param-value>
</init-param>
<init-param>
<param-name>height</param-name>
<param-value>20</param-value>
</init-param>
<init-param>
<param-name>codeCount</param-name>
<param-value>4</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ValidateCodeServlet</servlet-name>
<url-pattern>/ValidateCodeServlet</url-pattern>
</servlet-mapping>
3、Serlvert
package valdateCode;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ValidateCodeServlet extends HttpServlet {
/**
* serialVersionUID:TODO(用一句話描述這個變數表示什麼)
*
*/
private static final long serialVersionUID = 1L;
//驗證圖片的寬度
private int width=60;
//驗證圖片的高度
private int height=20;
//驗證碼字元個數
private int codeCount=4;
private int x=0;
//字型高度
private int fontHeight;
private int codeY;
char[] codeSequence={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public ValidateCodeServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//定義映像buffer
BufferedImage buffImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g=buffImg.createGraphics();
//建立一個隨機數產生器類
Random random=new Random();
//將映像填充為白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
//建立字型,字型的大小應該根據圖片的高度來定
Font font=new Font("Fixedsys",Font.PLAIN,fontHeight);
//設定字型
g.setFont(font);
//畫邊框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
//隨機產生160條幹擾線,使映像中的認證碼不易被其他程式探測到
//g.setColor(Color.LIGHT_GRAY);
g.setColor(Color.PINK);
for(int i=0;i<160;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(12);
int y1=random.nextInt(12);
g.drawLine(x, y, x+x1, y+y1);
}
//randomCode用於儲存隨機產生的驗證碼,以便使用者登入後進行驗證
StringBuffer randomCode=new StringBuffer();
int red=0,green=0,blue=0;
//隨機產生codeCount數位驗證碼
for(int i=0;i<codeCount;i++){
//得到隨機產生的驗證碼數字
String strRand=String.valueOf(codeSequence[random.nextInt(36)]);
//產生隨機的顏色分量來構造顏色值,這樣輸出的每位元字的顏色值都將不同
red=random.nextInt(255);
//green=random.nextInt(255);
green=random.nextInt(125);
blue=random.nextInt(255);
//用隨機產生的顏色將驗證碼繪製到映像中
g.setColor(new Color(red,green,blue));
g.drawString(strRand, (i+1)*x, codeY);
//將產生的四個隨機數組合在一起。
randomCode.append(strRand);
}
//將四位元字的驗證碼儲存到session中
HttpSession session=request.getSession();
session.setAttribute("validataCode", randomCode.toString());
//禁止映像緩衝
response.setHeader("Paragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
//將映像輸出到servlet輸出資料流中
ServletOutputStream sos=response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
/**
* 初始化驗證圖片屬性
*/
public void init() throws ServletException {
//從web.xml中擷取初始資訊
//寬度
String strWidth=this.getInitParameter("width");
//高度
String strHeight=this.getInitParameter("height");
//字元個數
String strCodeCount=this.getInitParameter("codeCount");
//將配置資訊轉換成數值
try{
if(strWidth!=null&&strWidth.length()!=0){
width=Integer.parseInt(strWidth);
}
if(strHeight!=null&&strHeight.length()!=0){
height=Integer.parseInt(strHeight);
}
if(strCodeCount!=null&strCodeCount.length()!=0){
codeCount=Integer.parseInt(strCodeCount);
}
}catch(NumberFormatException e){
}
x=width/(codeCount+1);
fontHeight=height-2;
codeY=height-4;
}
}