java实现图片验证码

本文实例为大家分享了java实现图片验证码的具体代码,供大家参考,具体内容如下

目的:

1) 验证操作者是否是人

2) 防止表单重复提交

生成验证码的要点:

1) 使用java代码生成图片对象

BufferedImage

2) 使用Random生成随机字符串

3) 将图片对象用

ImageIO.write(图片对象, "jpeg|png", 响应字节输出流)
返回给客户端浏览器

验证验证码:

要点:

1) 将验证码文字存入session作用域

2) 表单提交时,对比session中的验证码和表单中的验证码

CaptchaUtils.java

package cn.seeker.utils;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.List;
 
public class CaptchaUtil {
 
    public static String [] fuhao = {"+","-","*","/"};
    public static int num = 0;
 
    //生成随机算式
    public static String random(){
 
        List list = new ArrayList();
        Random ran = new Random();
        int n1 = ran.nextInt(10);
        int n2 = ran.nextInt(10);
        String f = fuhao[ran.nextInt(fuhao.length)];
        StringBuilder sb = new StringBuilder(4);
 
        switch (f){
            case "+":
                num = n1+n2;
                break;
            case "-":
                num =n1-n2;
                break;
            case "*":
                num = n1*n2;
                break;
            case "/":
                if(n2 == 0){
                    n2 = ran.nextInt(10)+1;
                    num = n1/n2;
                }else{
                    num = n1/n2;
                }
                break;
        }
        sb.append(n1);
        sb.append(f);
        sb.append(n2);
        sb.append("=");
 
        return sb.toString();
    }
    public static void outputImage(String str, OutputStream os){
        Random ran = new Random();
        //创建图片对象
        BufferedImage img = new BufferedImage(100,40, BufferedImage.TYPE_INT_RGB);
        //获取画布
        Graphics g = img.getGraphics();
        //设置背景
        g.setColor(Color.white);
        g.fillRect(0,0,100,40);
        //写字
        g.setColor(Color.black);
        g.setFont(new Font("微软雅黑",Font.PLAIN,30));
        g.drawString(str,10,40);
        //随机三条线
        g.drawLine(ran.nextInt(100),ran.nextInt(40),
                ran.nextInt(100),ran.nextInt(40));
        g.drawLine(ran.nextInt(100),ran.nextInt(40),
                ran.nextInt(100),ran.nextInt(40));
        g.drawLine(ran.nextInt(100),ran.nextInt(40),
                ran.nextInt(100),ran.nextInt(40));
        // 4. 输出结果
        // 常见的压缩格式:jpeg(有损压缩), png(无损压缩) ...
        try {
            ImageIO.write(img, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
 
}

regist.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/10/14
  Time: 15:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    注册
    


        输入验证码:    
 

CaptchaServlet.java

package cn.seeker.controller;
 
import cn.seeker.utils.CaptchaUtil;
 
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 java.io.IOException;
 
@WebServlet(urlPatterns = "/captcha.png")
public class CaptchaServlet extends HttpServlet {
 
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        response.setContentType("image/png");
        //获取随机字符串
        String random = CaptchaUtil.random();
        //输出图片
        CaptchaUtil.outputImage(random,response.getOutputStream());
        //存入结果
        request.getSession().setAttribute("res",CaptchaUtil.num);
 
    }
 
 
}

registServlet.jsp

package cn.seeker.controller;
 
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 java.io.IOException;
 
@WebServlet(urlPatterns = "/regist")
public class registServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cap = req.getParameter("cap");
        Integer res = (Integer)req.getSession().getAttribute("res");
        if(Integer.parseInt(cap) == res) {
            // 填写正确,注册成功
            req.getSession().removeAttribute("res");
            System.out.println("注册成功");
            resp.sendRedirect("/index.jsp");
 
        } else {
            req.setAttribute("error", "验证码不正确");
            req.getRequestDispatcher("/jsp/regist.jsp").forward(req,resp);
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(java实现图片验证码)