jsp生成验证码的代码

效果图:


loginProcess.jsp

java 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <% String captcha=request.getParameter("captcha");%>
    <% String captcha_session=(String)session.getAttribute("captchaCode");%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
     if (captcha.equals(captcha_session))
    	 out.print("验证码正确~!");
     else
    	 out.print("验证码不正确~!");
%>
</body>
</html>
java 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登录页面之验证码原理</title>
    <script>
        // JavaScript code to refresh captcha every 30 seconds
        function refreshCaptcha() {
            var img = document.getElementById("captchaImg");
            img.src = "./abc?" + new Date().getTime(); // add timestamp to force reload
        }
        setInterval(refreshCaptcha, 30000); // refresh captcha every 30 seconds
    </script>
</head>
<body>
    <h1>登录页面之验证码原理</h1>
    <form action="loginProcess.jsp" method="post">
        <div>
            <label for="username">姓名:</label>
            <input type="text" id="username" name="username">
        </div>
        <div>
            <label for="password">密码:</label>
            <input type="password" id="password" name="password">
        </div>
        <div>
            <label for="captcha">验证码:</label>
            <input type="text" id="captcha" name="captcha">
            <img id="captchaImg" width=100 src="./abc" alt="Captcha Image" onclick="refreshCaptcha()">
            <button type="button" onclick="refreshCaptcha()">刷新验证码</button>
        </div>
        <div>
            <button type="submit">登录</button>
        </div>
    </form>
</body>
</html>
java 复制代码
package src;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/abc")
public class GenerateCaptchaServlet extends HttpServlet {
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set content type of the response
        response.setContentType("image/jpeg");

        // Create a random captcha code
        String captchaCode = generateRandomCode(6); // Generate 6-character random code
        // Store the captcha code in session for validation
        request.getSession().setAttribute("captchaCode", captchaCode);

        // Create a BufferedImage for captcha image
        int width = 200;
        int height = 50;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // Draw the captcha code on the image
        g2d.setFont(new Font("Arial", Font.BOLD, 24));
        g2d.setColor(Color.RED);
        g2d.drawString(captchaCode, 50, 30);

        // Dispose the graphics
        g2d.dispose();

        // Output the image as JPEG to the client
        OutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpeg", out);
        out.close();
    }

    private String generateRandomCode(int length) {
        String charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(charset.length());
            sb.append(charset.charAt(index));
        }
        return sb.toString();
    }
}
相关推荐
毕设源码-朱学姐1 分钟前
【开题答辩全过程】以 基于JAVA的市级非物质文化遗产交流平台为例,包含答辩的问题和答案
java·开发语言
小学鸡!28 分钟前
Spring Boot通过手机号获取归属地
java·spring boot
pedestrian_h1 小时前
操作系统-线程
android·java·开发语言
A-code1 小时前
C/C++ 中 void* 深度解析:从概念到实战
c语言·开发语言·c++·经验分享·嵌入式
whltaoin2 小时前
【JAVA全栈项目】弧图图-智能图床 SpringBoot+Vue3 :[框架开荒:一文全步骤打通前后端项目全流程]
java·spring boot·vue·开源项目·全栈·cos
Fu1co2 小时前
【Spring Boot】Spring Boot解决循环依赖
java·spring boot·spring
国服第二切图仔2 小时前
Rust中泛型函数实现不同类型数据的比较
开发语言·后端·rust
我命由我123453 小时前
Derby - Derby 服务器(Derby 概述、Derby 服务器下载与启动、Derby 连接数据库与创建数据表、Derby 数据库操作)
java·运维·服务器·数据库·后端·java-ee·后端框架
技术砖家--Felix3 小时前
Spring Boot入门篇:快速搭建你的第一个Spring Boot应用
java·开发语言·音视频
国服第二切图仔3 小时前
Rust开发之使用Trait对象实现多态
开发语言·算法·rust