博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Java】登录操作中随机生成验证码的工具类
阅读量:5069 次
发布时间:2019-06-12

本文共 6476 字,大约阅读时间需要 21 分钟。

效果图:

工具类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判断):

获取验证码

后台验证验证码的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项目,依赖为:

javax.servlet
javax.servlet-api
3.1.0
javax.servlet.jsp
javax.servlet.jsp-api
2.3.1

 

转载于:https://www.cnblogs.com/to-red/p/11260628.html

你可能感兴趣的文章
4.9 Parser Generators
查看>>
redis集群如何清理前缀相同的key
查看>>
redis7--hash set的操作
查看>>
20.字典
查看>>
Python 集合(Set)、字典(Dictionary)
查看>>
oracle用户锁定
查看>>
(转)盒子概念和DiV布局
查看>>
Android快速实现二维码扫描--Zxing
查看>>
获取元素
查看>>
nginx+lighttpd+memcache+mysql配置与调试
查看>>
proxy写监听方法,实现响应式
查看>>
前端工具----iconfont
查看>>
Azure Site Recovery 通过一键式流程将虚拟机故障转移至 Azure虚拟机
查看>>
Hello China操作系统STM32移植指南(一)
查看>>
cocos2dx CCEditBox
查看>>
VC++2012编程演练数据结构《8》回溯法解决迷宫问题
查看>>
第一阶段冲刺06
查看>>
WIN下修改host文件并立即生效
查看>>
十个免费的 Web 压力测试工具
查看>>
ckeditor 粘贴后去除html标签
查看>>