后台生成图片验证码

有时候需要后台生成图片验证码,下面是一个方法

 后台生成:

package socialPractise.controller.register;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
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;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import socialPractise.template.ResponseTemplate;

@Controller
public class VerifyController{
    // 图片高度
    private static final int IMG_HEIGHT = 100;
    // 图片宽度
    private static final int IMG_WIDTH = 30;
    // 验证码长度
    private static final int CODE_LEN = 4;
    
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "test";
    }
    
    @RequestMapping("/ImageGen")
    @ResponseBody
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 用于绘制图片,设置图片的长宽和图片类型(RGB)
        BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
        // 获取绘图工具
        Graphics graphics = bi.getGraphics();
        graphics.setColor(new Color(100, 230, 200)); // 使用RGB设置背景颜色
        graphics.fillRect(0, 0, 100, 30); // 填充矩形区域

        // 验证码中所使用到的字符
        char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
        String captcha = ""; // 存放生成的验证码
        Random random = new Random();
        for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
            int index = random.nextInt(codeChar.length);
            // 随机生成验证码颜色
            graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));
            // 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
            graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
            captcha += codeChar[index];
        }
        // 将生成的验证码code放入sessoin中
        HttpSession session = req.getSession();
        session.setAttribute("code", captcha);
        
        System.out.println(session.getId());
        // 通过ImageIO将图片输出
        ImageIO.write(bi, "JPG", resp.getOutputStream());
    }
    
    @RequestMapping("/checkCode")
    @ResponseBody
    protected ResponseTemplate checkCode(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 获取存放在session中的验证码
        HttpSession session = req.getSession();
        System.out.println(session.getId());
        String code = (String) session.getAttribute("code");
        System.out.println(code);
        // 获取页面提交的验证码
        String inputCode = req.getParameter("code");
        System.out.println(inputCode);
        if(code.toLowerCase().equals(inputCode.toLowerCase())) { // 验证码不区分大小写
            return new ResponseTemplate(0, "验证码正确", null);
        } else { // 验证失败
            return new ResponseTemplate(1, "验证码错误", null);
        }
    }

}

前端验证:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.0.js">
</script>
<script type="text/javascript">
//提交序列化表单
function flushCode() {
    // 每次刷新的时候获取当前时间,防止浏览器缓存刷新失败
    var time = new Date();
    document.getElementById("scode").src = "http://localhost:8080/ImageGen?time=" + time;
}
</script>

</head>
<body>
<form action="http://localhost:8080/checkCode" method="post">
    请输入验证码:<input type="text" name="code">
    <input type="submit" value="确定">
</form>
<!--  <img alt="验证码" id="scode" src="<%=request.getContextPath() %>/ImageGen" >-->
<img alt="验证码" id="scode" src="http://localhost:8080/ImageGen" >
<a href="#" onclick="javascript:flushCode();">看不清?</a>
</body>
</html>
原文地址:https://www.cnblogs.com/liyafei/p/8325239.html