@WebServlet("/checkCodeServlet")publicclassCheckCodeServletextendsHttpServlet{protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width =100;
int height =50;//1.創建一對象,在內存中圖片(驗證碼圖片對象)
BufferedImage image =newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//2.美化圖片//2.1 填充背景色
Graphics g = image.getGraphics();//畫筆對象
g.setColor(Color.PINK);//設置畫筆顏色
g.fillRect(0,0,width,height);//2.2畫邊框
g.setColor(Color.BLUE);
g.drawRect(0,0,width -1,height -1);
String str ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";//生成隨機角標
Random ran =newRandom();for(int i =1; i <=4; i++){
int index = ran.nextInt(str.length());//獲取字符
char ch = str.charAt(index);//隨機字符//2.3寫驗證碼
g.drawString(ch+"",width/5*i,height/2);}//2.4畫干擾線
g.setColor(Color.GREEN);//隨機生成座標點for(int i =0; i <10; i++){
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);}//3.將圖片輸出到頁面展示
ImageIO.write(image,"jpg",response.getOutputStream());}protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);}}
通過jsp生成驗證碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><%@page import="java.awt.image.BufferedImage"%><%@page import="java.awt.Graphics2D"%><%@page import="java.awt.Color"%><%@page import="java.awt.Font"%><%@page import="javax.imageio.ImageIO"%><%@page import="java.util.Random"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>驗證碼</title></head><body><%
int width =60;//定義圖片的寬度
int height =20;//定義圖片的高度 // 創建具有可訪問圖像數據緩衝區的Image
BufferedImage buffImg =newBufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();// 創建一個隨機數生成器
Random random =newRandom();//將圖像填充爲 白色
g.setColor(Color.WHITE);
g.fillRect(0,0, width, height);// 創建字體,字體的大小應該根據圖片的高度來定
Font font =newFont("Times New Roman", Font.PLAIN,18);// 設置字體
g.setFont(font);// 畫邊框
g.setColor(Color.BLACK);
g.drawRect(0,0, width -1, height -1);// 隨機產生160條幹擾線 ,使圖像中的驗證碼不易被其它程序探測到
g.setColor(Color.LIGHT_GRAY);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 =newStringBuffer();
int red =0, green =0, blue =0;// 隨機產生4位數字的驗證碼 for(int i =0; i <4; i++){// 得到隨機產生的驗證碼數字
String strRand = String.valueOf(random.nextInt(10));// 產生隨機的顏色分量來構造顏色值 ,這樣輸出的每位數字的顏色值都將不同
red = random.nextInt(110);
green = random.nextInt(50);
blue = random.nextInt(50);// 用隨機產生的顏色將驗證碼繪製到圖像中
g.setColor(newColor(red, green, blue));
g.drawString(strRand,13* i +6,16);//將產生的四個隨機數組合在一起
randomCode.append(strRand);}// 將四位數字的驗證碼保存到session中 //HttpSession session = request.getSession();
session.setAttribute("randomCode", randomCode.toString());// 禁止圖像緩存
response.setHeader("Pragma","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();//sos = null;
out.clear();
out = pageContext.pushBody();%></body></html>
在登錄界面顯示驗證碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head lang="en"><meta charset="UTF-8"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登錄界面</title><script src="./js/jquery-1.9.0.min.js"></script><script type="text/javascript">$(function(){$("#loginform_submit").click(function(){if(checkInput()){$("#form1").submit();}else{returnfalse;}});});functioncheckInput(){var flag =true;//判斷用戶名 if($("input[name=username]").val()==null||$("input[name=username]").val()==""){alert("用戶名不能等於空");$("input[name=username]").focus();
flag =false;return;}//判斷密碼 if($("input[name=password]").val()==null||$("input[name=password]").val()==""){alert("密碼不能等於空");$("input[name=password]").focus();
flag =false;return;}//判斷驗證碼 if($("#validationCode").val()==null||$("#validationCode").val()==""){alert("驗證碼不能爲空");$("#validationCode").focus();
flag =false;return;}return flag;}</script></head><body><div id="loginpanelwrap" align="center"><div><div>登錄</div></div><form id="form1" action="do_login.jsp" method="post"><table><tr><td><label>用戶名:</label><input id="username" type="text" name="username"/><br></td></tr></table><label>密碼:</label><input type="password" name="password" id="password"/><br><label>驗證碼:</label><input type="text" name="validationCode" id="validationCode"/><!--<img id="validationCode_img" src="validate.jsp"><br>--><img src="validate.jsp" id="picture" onClick="change()" id="picture"><!--點擊驗證碼可以進行動態刷新 --><!--刷新驗證碼的src--><script>functionchange(){var pic=document.getElementById("picture");var i=Math.random();//目的是使頁面不一樣
pic.src="validate.jsp?id="+i;}</script><table><tr><input type="submit" id="loginform_submit" value="登錄"/></tr></table></form></div></body></html>
用js直接生成驗證碼並驗證
<html><head><title>純字驗證碼</title><meta http-equiv='content-type' content='text/html;charset=utf-8'/><script type='text/javascript' src='jquery-1.7.2.js'></script><script type='text/javascript'>var code ;//在全局定義驗證碼 functioncreateCode(){
code ="";var codeLength =4;//驗證碼的長度 var checkCode = document.getElementById("code");var random =newArray(0,1,2,3,4,5,6,7,8,9,'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');//隨機數 for(var i =0; i < codeLength; i++){//循環操作 var index = Math.floor(Math.random()*36);//取得隨機數的索引(0~35)
code += random[index];//根據索引取得隨機數加到code上 }
checkCode.value = code;//把code值賦給驗證碼 }//校驗驗證碼 functionvalidate(){var inputCode = document.getElementById("input").value.toUpperCase();//取得輸入的驗證碼並轉化爲大寫 if(inputCode.length <=0){//若輸入的驗證碼長度爲0 alert("請輸入驗證碼!");//則彈出請輸入驗證碼 }elseif(inputCode != code ){//若輸入的驗證碼與產生的驗證碼不一致時 alert("驗證碼輸入錯誤!@_@");//則彈出驗證碼輸入錯誤 createCode();//刷新驗證碼
document.getElementById("input").value ="";//清空文本框 }else{//輸入正確時 alert("合格!^-^");}}</script><style type='text/css'>
#code{
font-family:Arial,宋體;
font-style:italic;
color:green;
border:0;
padding:2px 3px;
letter-spacing:3px;
font-weight:bolder;}</style></head><body οnlοad='createCode()'><div>驗證碼:
<input type ="text" id ="input"/><input type="button" id="code" οnclick="createCode()" style="width:60px" title='點擊更換驗證碼'/><input type ="button" value ="驗證" onclick ="validate()"/></div></body></html>