Java简易加减乘图像验证码生成

本文介绍了一个使用Java实现的验证码生成器,该生成器能够生成包含简单数学运算的验证码图片,并提供了一个示例控制器代码和前端展示页面。文章还展示了如何通过随机颜色、线条干扰等方式提高验证码的安全性。

Java:TestYanzhengMaActionController.java

package com.suyin.web.front.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @author gyx
 */
@Controller
@RequestMapping("/yzm")
public class TestYanzhengMaActionController {
    @RequestMapping("yanzhengma.do")
    public String toProductList(HttpServletRequest request, HttpServletResponse response) {
        return "/front/test/yanzhengma";
    }

    @RequestMapping("/validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int width = 126;
        int height = 48;
        int fontHeight = 32;
        
        // 定义图像buffer-画布
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //创建2D画笔
        Graphics2D g = buffImg.createGraphics();
        
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        
        // 创建字体,字体的大小应该根据图片的高度来定。
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        // 设置字体。
        g.setFont(font);
        
        // 画边框。
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        
        // 随机产生干扰线
        g.setColor(Color.BLACK);
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(20);
            int yl = random.nextInt(20);
            g.drawLine(x, y, x + xl, y + yl);
        }
        
        //randomCode-用于保存随机产生的验证码,即画布上面的图画
        String randomCode = "";
        int validateCode = 0;
        
        /**
         * 加减数字控制在10以内
         */
        int a = random.nextInt(4) + 5;
        int b = random.nextInt(4);
        
        //随机加减乘,除法要处理意外,忽略
        int c = random.nextInt(3);
        switch (c) {
        case 0:
            randomCode = a + "加" + b;
            validateCode = a + b;
            break;
        case 1:
            randomCode = a + "减" + b;
            validateCode = a - b;
            break;
        case 2:
            randomCode = a + "乘" + b;
            validateCode = a * b;
            break;
        default:
            break;
        }
        
        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        
        // 用随机产生的颜色将验证码绘制到图像中。
        g.setColor(new Color(red, green, blue));
        g.drawString(randomCode, 2, 30);
        
        //保存session,用于登录验证
        request.getSession().setAttribute("validateCode", validateCode);
        
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        
        //将图像输出->流打印
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
    }
}

 

 

jsp:yanzhengma.jsp

<%@ page trimDirectiveWhitespaces="true"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="IE=edge,chrome=1" />
<title>验证码</title>

<!--需要--jquery-->
<script src="<c:url value="/app/jquery-1.8.2.min.js"></c:url>" type="text/javascript"></script>
<script type="text/javascript">
function createCode(){
    var imgSrc = $("#code");
    imgSrc.attr("src","validateCode.do?temp=" + Math.floor(Math.random() * ( 10000 + 1)));
}

$(function() {
    createCode();
});
</script>
</head>
<body>
    <div>
            <input name="vericode" type="text" id="validateCode" placeholder="请输入验证码" />
            <br/>
            <br/>
            <img id="code" src="" onclick="createCode();" alt="看不清楚?点击刷新">
            <a onclick="createCode();" style="cursor: pointer;">换一张</a> 
    </div>
</body>
</html>

转载于:https://my.oschina.net/pvpCC9IFwqz4/blog/727069

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值