欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

服务器端生成的验证码技术(Java)

程序员文章站 2022-05-19 19:25:10
...

准备工作

(1) 以Myeclipse 2017为例,创建Web Project并建包
(2) src源代码文件中创建一个Servlet**(注意:这里为other…->Web->Servlet)**
(3)删除不需要的代码并用doGet调用doPost函数(代码写在一个函数中

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckCode extends HttpServlet {

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

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

    }
}

验证码的Servlet类

import java.awt.Color;
import java.awt.Graphics2D;
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;

public class CheckCode extends HttpServlet {
    //验证码图片大小
    public final static int IMG_WIDTH = 50;
    public final static int IMG_HEIGHT = 30;
    //随机验证码集合
    public final static String  CHECK_STRING = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
    //验证码个数
    public final static int CHECK_NUM = 4;

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

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建一个图片缓冲,图片类型为RGB
        BufferedImage img = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
        //拿到图片的画笔
        Graphics2D g2d = (Graphics2D)img.getGraphics();
        //将缓冲图片默认的黑色改为白色
        g2d.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
        //画出验证码
        for(int i=0; i<CHECK_NUM; i++){
            int randomNum = new Random().nextInt(CHECK_STRING.length());
            //根据随机数将字母强制转换为字符串
            String randomChar = String.valueOf(CHECK_STRING.charAt(randomNum));
            //随机颜色
            RandomColor(g2d);
            //画出一个验证码
            g2d.drawString(randomChar, 5 + (15 * i), 15);
        }

        /**
         * 对验证码增加干扰,可以是点也可以是线等
         */
        for(int i=0; i<4; i++){
            //随机产生划线坐标
            int x1 = new Random().nextInt(IMG_WIDTH);
            int y1 = new Random().nextInt(IMG_HEIGHT);
            int x2 = new Random().nextInt(IMG_WIDTH);
            int y2 = new Random().nextInt(IMG_WIDTH);
            RandomColor(g2d);
            g2d.drawLine(x1, y1, x2, y2);
        }
        //向客户端发送jpg图片
        ImageIO.write(img, "jpg", response.getOutputStream());
    }
    /**
     * 设置画笔颜色为随机颜色
     * @param g2d
     */
    public void RandomColor(Graphics2D g2d){
        //RGB三色参数
        int r = new Random().nextInt(255);
        int g = new Random().nextInt(255);
        int b = new Random().nextInt(255);
        //设置颜色
        g2d.setColor(new Color(r, g, b));
    }
}

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <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="验证码">
    <link rel="stylesheet" type="text/css" href="styles.css">

  </head>

  <body>
  <div style="color: red">没人要的登陆界面</div>
  <form action="#" method="post">
    账号  <input name="username" type="text" value=""/><br>
    密码  <input name="password" type="text" value=""/><br>
    验证码  <input name="checknum" type="text"><img src="servlet/CheckCode" onclick="this.src='servlet/CheckCode?' + Math.random();"> <br>
    <input type="submit" value="确认"><input type="reset" value="重新输入">
  </form>

  </body>
</html>

打开游览器输入路径>效果如下
服务器端生成的验证码技术(Java)
路径格式http://localhost:8080/CheckCode/index.jsp
http+本机地址+tomcat默认端口号+工程文件名+ 页面名称(也可以为Servlet类路径)

相关标签: 验证码