【Java】登录操作中随机生成验证码的工具类

效果图:

工具类CreateImageCode.java:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class CreateImageCode {
    private int width = 70;
    private int height = 27;
    private int codeCount = 4;
    // 干扰线数
    //private int lineCount = 10;
    // 验证码图片Buffer
    // 验证码
    private String code = null;
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    private BufferedImage buffImg = null;

    Random random = new Random();

    public CreateImageCode() {
        createImage();
    }

    public CreateImageCode(int width, int height) {
        this.width = width;
        this.height = height;
        createImage();
    }

    public CreateImageCode(int width, int height, int codeCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        createImage();
    }

    public CreateImageCode(int width, int height, int codeCount, int lineCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        //this.lineCount = lineCount;
        createImage();
    }

    // 生成图片
    private void createImage() {
        int fontWidth = width / codeCount;// 字体宽度。
        int fontHeight = height - 5;// 字体高度。
        int codeY = height - 8;

        // 得到图片
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = buffImg.getGraphics();

        // 设置背景色
        g.setColor(getRandColor(249, 250));
        g.fillRect(0, 0, width, height);

        // 设置边框
        //g.setColor(getRandColor(200, 250));
        //g.drawRect(1, 1, width - 2, height - 2);

        // 设置字体
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        g.setFont(font);

        /*// 设置干扰线
        for (int i = 0; i < lineCount; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.setColor(getRandColor(1, 255));
            g.drawLine(x1, y1, x2, y2);
        }*/
        /*// 添加噪点
        float yawpRate = 0.01f;// 噪声率
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);

            buffImg.setRGB(x, y, random.nextInt(255));
        }*/
        String str1 = randomStr(codeCount);// 得到随机字符
        this.code = str1;
        for (int i = 0; i < codeCount; i++) {
            String strRand = str1.substring(i, i + 1);
            g.setColor(getRandColor(50, 250));
            // g.drawString(a,x,y);
            // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处

            g.drawString(strRand, i * fontWidth + 3, codeY);
        }
    }
    // 得到随机字符
    private String randomStr(int n) {
        String str1 = "1234567890";
        String str2 = "";
        int len = str1.length() - 1;
        double r;
        for (int i = 0; i < n; i++) {
            r = (Math.random()) * len;
            str2 = str2 + str1.charAt((int) r);
        }
        return str2;
    }
    // 得到随机颜色
    private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
        sos.close();

    }

}

在servlet中使用此工具类,输出验证码到网页:

package com.utils;

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(name = "GetImageCodeServlet",urlPatterns = {"/servlet/code.servlet"})
public class GetImageCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jepg");
        // 控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        // 创建图片
        CreateImageCode image = new CreateImageCode();
        String str = image.getCode();
        // 存入Session
//        System.out.println("验证码为"+str);
        request.getSession().setAttribute("code",str);
        // 输出到网页
        image.write(response.getOutputStream());
    }
}

JSP中在表单显示此图片(演示时不使用Ajax,直接将form提交到另一个servlet判断):

    <form action="${pageContext.request.contextPath}/servlet/codeTest.servlet">
        <input type="text" name="code">
        <img src="${pageContext.request.contextPath}/servlet/code.servlet"
             onclick="javascript:this.src='${pageContext.request.contextPath}/servlet/code.servlet?rm='+Math.random()"
             alt="获取验证码">
        <input type="submit" value="验证">
    </form>

后台验证验证码的servlet:

package com.utils;

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(name = "CodeTestServlet" ,urlPatterns = {"/servlet/codeTest.servlet"})
public class CodeTestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        if (code.equals(request.getSession().getAttribute("code"))) {
            System.out.println("验证成功,验证码为:" + request.getSession().getAttribute("code"));
            // response.sendRedirect(getServletContext().getContextPath()+"/login.jsp");
        }else{
            System.out.println("验证失败");
        }
    }
}

----

使用的是3.0的注解开发,web.xml中不需配置

若为maven项目,依赖为:

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>

 

posted @ 2019-07-28 19:53  HanJunOvO  阅读(663)  评论(0编辑  收藏  举报