Java实现验证码的生成

今天按组长要求,实现了前端登录界面验证码生成及识别功能,确保网站的安全性,无聊之余,总结今天的工作内容。下面是部分代码的讲解。

上图为前端代码,img标签里加入src的链接,CheckCodeAction.java为后台验证码的生成和验证。changImg()鼠标点击事件为调用后台CheckCodeAction生成验证码,打印到前端。changImg()事件的实现如下:

public class CheckCodeAction extends HttpServlet {

private Gson gson = new Gson();
private HashMap<String, Object> map;
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    String checkcode = request.getParameter("checkcode");
    String last_yzmcode = (String) session.getAttribute("yzmcode");
    map = new HashMap<>();
    if (checkcode != null) {
        PrintWriter pw = response.getWriter();
        if (checkcode.equalsIgnoreCase(last_yzmcode)) {
            map.put("result", "OK");
            String jstr = gson.toJson(map, HashMap.class);
            pw.println(jstr);
            return;
        } else {
            map.put("result", "ERROR");
            String jstr = gson.toJson(map, HashMap.class);
            pw.println(jstr);
            return;
        }
    }
    //告诉客户端,输出的格式


    response.setContentType("image/jpeg");


    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);


    int width = 80;
    int height = 40;
    int lines = 7;
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


    Graphics g = img.getGraphics();


    //设置背景色
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);


    //设置字体
    g.setFont(new Font("黑体", Font.BOLD, 22));


    //随机数字
    Random r = new Random(new Date().getTime());
    String yzmcode = "";
    String str[] = {"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"};
    for (int i = 0; i < 4; i++) {
        int a = r.nextInt(36);
        int y = 20 + r.nextInt(10);//10~30范围内的一个整数,作为y坐标
        String s = str[a];
        Color c = new Color(r.nextInt(200), r.nextInt(200), r.nextInt(200));
        g.setColor(c);
        g.drawString("" + s, 5 + i * width / 4, y);
        yzmcode += s;
    }


    //干扰线
    for (int i = 0; i < lines; i++) {
        Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
        g.setColor(c);
        g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
    }


    g.dispose();//类似于流中的close()带动flush()---把数据刷到img对象当中


    ImageIO.write(img, "JPG", response.getOutputStream());


    session.setAttribute("yzmcode", yzmcode);
}

}

猜你喜欢

转载自blog.csdn.net/xiaoxiao_yang77/article/details/78227214