jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% request.setCharacterEncoding("UTF-8"); %>
<% response.setCharacterEncoding("UTF-8"); %>
<html>
<head><title>用户注册</title>
</head>
<body>
<form action="" method="get">登录名:<input type="text" name="username"><br><br>密码:<input type="password" name="password"><br><br>验证码:<input type="text" name="authcode"><br><br><img id =“authcode” src="authcode" alt="验证码"><br><button onclick="refreshcode()">刷新验证码</button><input type="submit" value="注册">
</form>
</body>
<script>function refreshcode() {console.log("刷新验证码");authcode.src = "authcode?t=" + new Date().getTime();}
</script>
</html>
servlet文件
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;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;@WebServlet("/guest/authcode")
public class AuthCodeServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("image/jpg");String authCode = StringAuth.getAuth();HttpSession session = req.getSession();System.out.println("验证码:"+authCode);session.setAttribute("authCode", authCode);//在内存中创建一张图片int width = 300;int height = 100;BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取Graphics2D对象以绘制图像Graphics2D g2d = bufferedImage.createGraphics();// 设置抗锯齿渲染提示g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 设置字体样式Font font = new Font("Arial", Font.BOLD, 24);g2d.setFont(font);// 设置文本颜色g2d.setColor(Color.BLUE);// 在图片上绘制字符串FontMetrics fm = g2d.getFontMetrics();Rectangle2D rect = fm.getStringBounds(authCode, g2d);int x = (width - (int) rect.getWidth()) / 2;int y = ((height - (int) rect.getHeight()) / 2) + fm.getAscent();g2d.drawString(authCode, x, y);// 释放资源g2d.dispose();ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());}
}
生成四位验证码的Java文件
import java.util.Random;public class StringAuth {private static final Random ra = new Random(System.currentTimeMillis());public static String getAuth(){StringBuilder sb = new StringBuilder();for (int i = 0; i < 4; i++) {int r = ra.nextInt(52);if(r<26){r+=65;}else{r+=71;}char c = (char) r;sb.append(c);}return sb.toString();}
}