- @WebServlet("/captcha")
- public class CaptchaServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static final int WIDTH = 100; // 图片宽度
- private static final int HEIGHT = 30; // 图片高度
- private static final int FONT_SIZE = 20; // 字体大小
- private static final int MAX_NUMBER = 10; // 随机数的最大值
- private static final int MAX_OFFSET = 5; // 随机误差的最大值
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // 生成随机算式
- Random random = new Random();
- int num1 = random.nextInt(MAX_NUMBER);
- int num2 = random.nextInt(MAX_NUMBER);
- char op = random.nextBoolean() ? '+' : '-';
- int result = op == '+' ? num1 + num2 : num1 - num2;
- String captcha = String.format("%d %c %d = ", num1, op, num2);
- // 将验证码和计算结果存储到 session 中
- HttpSession session = request.getSession();
- session.setAttribute("captcha", captcha);
- session.setAttribute("result", result);
- // 生成验证码图片
- BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
- Graphics2D g = image.createGraphics();
- g.setColor(Color.WHITE);
- g.fillRect(0, 0, WIDTH, HEIGHT);
- g.setColor(Color.BLACK);
- g.setFont(new Font("Arial", Font.PLAIN, FONT_SIZE));
- g.drawString(captcha, MAX_OFFSET, HEIGHT / 2 + FONT_SIZE / 2 - MAX_OFFSET);
- // 将验证码图片写入输出流中
- response.setContentType("image/png");
- OutputStream out = response.getOutputStream();
- ImageIO.write(image, "png", out);
- out.close();
- }
- }
-
-
-
- Result
res = new Result(); - // 生成随机算数运算符
- final Random random = new Random();
- int operatorIndex = random.nextInt(3);
- char operator = '+';
- switch (operatorIndex) {
- case 0:
- operator = '+';
- break;
- case 1:
- operator = '-';
- break;
- case 2:
- operator = '×';
- break;
- }
- // 生成随机算数操作数
- int operand1 = random.nextInt(10) + 1;
- int operand2 = random.nextInt(10) + 1;
- if (operator == '-') {
- while (operand1 < operand2) {
- operand1 = random.nextInt(10) + 1;
- operand2 = random.nextInt(10) + 1;
- }
- }
- // 计算结果
- int result = 0;
- String lowerCaseCode = "";
- switch (operator) {
- case '+':
- result = operand1 + operand2;
- lowerCaseCode = operand1 + "+" + operand2 + "=";
- break;
- case '-':
- result = operand1 - operand2;
- lowerCaseCode = operand1 + "-" + operand2 + "=";
- break;
- case '×':
- result = operand1 * operand2;
- lowerCaseCode = operand1 + "*" + operand2 + "=";
- break;
- }
第一部分是一个名为 CaptchaServlet 的 Java Servlet,用于生成验证码图片。第二部分是一个生成算式验证码的方法,返回一个包含算式和结果的字符串,以及一个 Result 对象。
在 CaptchaServlet 中,首先生成一个随机算式,包含两个随机数和一个随机运算符,然后将验证码和计算结果存储到 HttpSession 中。接着生成一个验证码图片,使用 Graphics2D 绘制验证码字符串,最后将验证码图片写入 HttpServletResponse 的输出流中。
在生成算式验证码的方法中,首先生成一个随机运算符和两个随机操作数,如果运算符是减法,则要保证被减数大于减数。然后根据运算符计算结果,并将算式和结果存储到一个字符串中,返回给调用者。同时,还生成一个 Result 对象,用于存储算式验证码的字符串和计算结果。