效果

2019-04-23-00-32-01----

代码

package com.ming.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

import static java.awt.image.BufferedImage.TYPE_INT_RGB;

/**
 * 生成验证码
 * @author ming
 */
public class AuthCode {
    public static final int AUTHCODE_LENGTH = 5; // 验证码长度
    public static final int SINGLECODE_WIDTH = 15; // 单个验证码宽度
    public static final int SINGLECODE_HEIGHT = 30; // 单个验证码高度
    public static final int SINGLECODE_GAP = 4; // 单个验证码之间间隔
    public static final int IMG_WIDTH = AUTHCODE_LENGTH * (SINGLECODE_WIDTH + SINGLECODE_GAP);
    public static final int IMG_HEIGHT = SINGLECODE_HEIGHT;
    public static final char[] CHARS = {'0','1', '2', '3', '4', '5', '6', '7', '8',
            '9','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
    static Random random = new Random();

    public static String getAuthCode(){
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0; i < 5; i++){
            stringBuffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return stringBuffer.toString();
    }

    public static BufferedImage getAuthImg(String authCode){
        BufferedImage bufferedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, TYPE_INT_RGB);
        // 获得画笔
        Graphics graphics = bufferedImage.getGraphics();
        // 设置颜色
        graphics.setColor(Color.RED);
        // 设置一个矩形
        graphics.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
        // 设置画笔颜色
        graphics.setColor(Color.BLACK);
        // 设置字体
        graphics.setFont(new Font("宋体", Font.PLAIN, SINGLECODE_HEIGHT + 5));
        // 输出验证码上数字
        char c;
        for (int i = 0; i < authCode.toCharArray().length; i++){
            // 取到字符
            c = authCode.charAt(i);
            // 画上字符
            graphics.drawString(c + "", i * (SINGLECODE_WIDTH + SINGLECODE_GAP)
                    + SINGLECODE_GAP / 2, IMG_HEIGHT);
        }
        Random random = new Random();
        // 干扰素
        for (int i = 0; i < 15; i++) {
            int x = random.nextInt(IMG_WIDTH);
            int y = random.nextInt(IMG_HEIGHT);
            int x2 = random.nextInt(IMG_WIDTH);
            int y2 = random.nextInt(IMG_HEIGHT);
            graphics.drawLine(x, y, x + x2, y + y2);
        }
        return bufferedImage;
    }
}

package com.ming.servlet;

import com.ming.util.AuthCode;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class getAuthCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取验证码字符串
        String authString = AuthCode.getAuthCode();

        req.getSession().setAttribute("authcode", authString);
        resp.setContentType("image/jpeg");
        resp.setDateHeader("expries", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        try{
            ImageIO.write(AuthCode.getAuthImg(authString), "JPG", resp.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
xiao
<form action="index.jsp" method="post">
    <img src="img" id="authImg"/><a href="#" onClick="window.location.reload()">看不清</a><br>
    <input type="text" name="inputCode">
    <%
        String inputCode = (String)request.getParameter("inputCode");
        String authCode = (String)session.getAttribute("authcode");
        if(inputCode!=null){
            if(inputCode.equals(authCode)){
                out.print("验证码正确!");
            }else{
                out.print("验证码错误!请重新输入!");
            }
        }
    %>
    <br>
    <input type="submit" value="提交">
</form>
</body>
</html>