程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> JSP + Servlet實現生成登錄驗證碼示例,servlet驗證碼

JSP + Servlet實現生成登錄驗證碼示例,servlet驗證碼

編輯:關於JSP

JSP + Servlet實現生成登錄驗證碼示例,servlet驗證碼


隨機生成四位數驗證碼,包括漢字,數字,英文大小寫。

1.Servlet類

package servlet;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PictureCheckCode extends HttpServlet {

   private static final long serialVersionUID = 1L; 

    public PictureCheckCode() { 
      super(); 
    } 

    public void destroy() { 
      super.destroy();  
    } 

    public void init() throws ServletException { 
      super.init(); 
    } 
    /*該方法主要作用是獲得隨機生成的顏色*/  
    public Color getRandColor(int s,int e){ 
      Random random=new Random (); 
      if(s>255) s=255; 
      if(e>255) e=255; 
      int r,g,b; 
      r=s+random.nextInt(e-s);  //隨機生成RGB顏色中的r值 
      g=s+random.nextInt(e-s);  //隨機生成RGB顏色中的g值 
      b=s+random.nextInt(e-s);  //隨機生成RGB顏色中的b值 
      return new Color(r,g,b); 
    } 

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("this is doGet method");
    this.doPost(request, response);

  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    //設置不緩存圖片 
    response.setHeader("Pragma", "No-cache"); 
    response.setHeader("Cache-Control", "No-cache"); 
    response.setDateHeader("Expires", 0); 
    //指定生成的響應圖片,一定不能缺少這句話,否則錯誤. 
    response.setContentType("image/jpeg"); 
    int width=80,height=35;   //指定生成驗證碼的寬度和高度 
    BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //創建BufferedImage對象,其作用相當於一圖片 
    Graphics g=image.getGraphics();   //創建Graphics對象,其作用相當於畫筆 
    Graphics2D g2d=(Graphics2D)g;    //創建Grapchics2D對象 
    Random random=new Random(); 
    Font mfont=new Font("楷體",Font.BOLD,16); //定義字體樣式 
    g.setColor(getRandColor(200,250)); 
    g.fillRect(0, 0, width, height);  //繪制背景 
    g.setFont(mfont);          //設置字體 
    g.setColor(getRandColor(180,200)); 

    //繪制100條顏色和位置全部為隨機產生的線條,該線條為2f 
    for(int i=0;i<100;i++){ 
      int x=random.nextInt(width-1); 
      int y=random.nextInt(height-1); 
      int x1=random.nextInt(6)+1; 
      int y1=random.nextInt(12)+1; 
      BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL); //定制線條樣式 
      Line2D line=new Line2D.Double(x,y,x+x1,y+y1); 
      g2d.setStroke(bs); 
      g2d.draw(line);   //繪制直線 
    } 
    //輸出由英文,數字,和中文隨機組成的驗證文字,具體的組合方式根據生成隨機數確定。 
    String sRand=""; 
    String ctmp=""; 
    int itmp=0; 
    //制定輸出的驗證碼為四位 
    for(int i=0;i<4;i++){ 
      switch(random.nextInt(3)){ 
        case 1:   //生成A-Z的字母 
           itmp=random.nextInt(26)+65; 
           ctmp=String.valueOf((char)itmp); 
           break; 
        case 2:   //生成漢字 
           String[] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};  
           //生成第一位區碼 
           int r1=random.nextInt(3)+11; 
           String str_r1=rBase[r1]; 
           //生成第二位區碼 
           int r2; 
           if(r1==13){ 
             r2=random.nextInt(7);   
           }else{ 
             r2=random.nextInt(16); 
           } 
           String str_r2=rBase[r2]; 
           //生成第一位位碼 
           int r3=random.nextInt(6)+10; 
           String str_r3=rBase[r3]; 
           //生成第二位位碼 
           int r4; 
           if(r3==10){ 
             r4=random.nextInt(15)+1; 
           }else if(r3==15){ 
             r4=random.nextInt(15); 
           }else{ 
             r4=random.nextInt(16); 
           } 
           String str_r4=rBase[r4]; 
           //將生成的機內碼轉換為漢字 
           byte[] bytes=new byte[2]; 
           //將生成的區碼保存到字節數組的第一個元素中 
           String str_12=str_r1+str_r2; 
           int tempLow=Integer.parseInt(str_12, 16); 
           bytes[0]=(byte) tempLow; 
           //將生成的位碼保存到字節數組的第二個元素中 
           String str_34=str_r3+str_r4; 
           int tempHigh=Integer.parseInt(str_34, 16); 
           bytes[1]=(byte)tempHigh; 
           ctmp=new String(bytes); 
           break; 
        default: 
           itmp=random.nextInt(10)+48; 
           ctmp=String.valueOf((char)itmp); 
           break; 
      } 
      sRand+=ctmp; 
      Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110)); 
      g.setColor(color); 
      //將生成的隨機數進行隨機縮放並旋轉制定角度 PS.建議不要對文字進行縮放與旋轉,因為這樣圖片可能不正常顯示 
      /*將文字旋轉制定角度*/ 
      Graphics2D g2d_word=(Graphics2D)g; 
      AffineTransform trans=new AffineTransform(); 
      trans.rotate((45)*3.14/180,15*i+8,7); 
      /*縮放文字*/ 
      float scaleSize=random.nextFloat()+0.8f; 
      if(scaleSize>1f) scaleSize=1f; 
      trans.scale(scaleSize, scaleSize); 
      g2d_word.setTransform(trans); 
      g.drawString(ctmp, 15*i+18, 14); 
    } 
    HttpSession session=request.getSession(true); 
    session.setAttribute("randCheckCode", sRand); 
    System.out.println(sRand);
    g.dispose();  //釋放g所占用的系統資源 
    ImageIO.write(image,"JPEG",response.getOutputStream()); //輸出圖片 
  }

}

2.web.xml配置

<servlet>
  <description>This is the description of my J2EE component</description>
  <display-name>This is the display name of my J2EE component</display-name>
  <servlet-name>PictureCheckCode</servlet-name>
  <servlet-class>servlet.PictureCheckCode</servlet-class>
 </servlet>

<servlet-mapping>
  <servlet-name>PictureCheckCode</servlet-name>
  <url-pattern>/pictureCheckCode</url-pattern>
 </servlet-mapping>

3.jsp頁面輸出驗證碼

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>登錄頁面</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">
<script language="javascript">
  function myReload() {
    document.getElementById("CreateCheckCode").src = document
        .getElementById("CreateCheckCode").src
        + "?nocache=" + new Date().getTime();
  }
</script>

</head>

<body>
  <form action="loginServlet" method="get">
      <p class="font tdheight">
        驗證碼:<input type="text" name="checkCode"
          > <img
          src="pictureCheckCode" id="CreateCheckCode" align="middle"
          > <br> <a href=""
          onclick="myReload()"
          > 看不清,換一個</a>
      </p>
      <br><input type="submit" value="提交"
            class="font" >

    </form>
</body>
</html>

4.後台Servlet判斷驗證碼是否與輸入一致

通過request.getParameter(“checkCode”)獲取輸入驗證碼,與session.getAttribute(“randCheckCode”)比較是否一致。

public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String code = request.getParameter("checkCode");
    HttpSession session = request.getSession();
    if (!code.equals(session.getAttribute("randCheckCode"))) {
      request.setAttribute("errormsg", "驗證碼不正確");
    } 
    System.out.println(request.getAttribute("errormsg"));
  }

運行結果:


以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持幫客之家。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved