首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 驗證碼大全:中文驗證碼實現

     編輯:關於JSP

中文驗證碼因筆畫複雜,提高自動識別難度,增強安全性。

ChineseVal.jsp 核心代碼

<%@ page pageEncoding="gb2312" contentType="image/jpeg" import="javax.imageio.*,java.util.*,java.awt.image.*,java.awt.*" %>
<%!
  Color getRandColor(Random random, int fc, int bc) {
    if (fc > 255) fc = 255;
    if (bc > 255) bc = 255;
    int r = fc + random.nextInt(bc - fc);
    int g = fc + random.nextInt(bc - fc);
    int b = fc + random.nextInt(bc - fc);
    return new Color(r, g, b);
  }
%>
<%
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
  int width = 130, height = 30;
  String base = "\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u538b\u6162\u53d4\u80cc\u7ec6..."; // 大量中文字
  int length = base.length();
  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  Graphics g = image.getGraphics();
  Random random = new Random();
  g.setColor(getRandColor(random, 188, 235));
  g.fillRect(0, 0, width, height);
  String[] fontTypes = {"\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66"};
  // 畫干擾字符
  g.setColor(getRandColor(random, 180, 199));
  g.setFont(new Font("Times New Roman", Font.PLAIN, 14));
  for (int i = 0; i < 4; i++) {
    g.drawString("@*@*@*@*@*@*@*", 0, 5 * (i + 2));
  }
  String sRand = "";
  for (int i = 0; i < 4; i++) {
    int start = random.nextInt(length);
    String rand = base.substring(start, start + 1);
    sRand += rand;
    g.setColor(getRandColor(random, 10, 150));
    g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD, 18 + random.nextInt(6)));
    g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);
  }
  session.setAttribute("rand", sRand);
  g.dispose();
  ImageIO.write(image, "JPEG", response.getOutputStream());
  out.clear();
  out = pageContext.pushBody();
%>

下文將說明調用方式與亂碼解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved