JAVA验证码制作

本文章是借鉴某宝上购买的SSM框架学习和本人自己的经验写的,如果有什么不好的看到的朋友多多谅解,毕竟是第一篇。

将代码贴出来,然后再一步一步来解释是怎么回事是怎么写的,为什么要这么写!

注意:写入session的时候用的Const.SESSION_SECURITY_CODE这个字符串是后台的一个常量工具类里面的字符串,可以自己定义一个字符串即可。

1.后台代码:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

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

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fh.util.Const;

@Controller
@RequestMapping
public class SecCodeController {

@RequestMapping("");

public void generate(HttpServletResponse response){

        ByteArrayOutputStream output = new ByteArrayOutputStream();  //创建字节数组流,用来写入随机生成的4位随机字符的图片流

        String code = drawImg(output);        //调用验证码图片生成方法,实现字节数组流写入和随机字符变量获取
        
        Subject currentUser = SecurityUtils.getSubject();  //获取当前用户的Suject
        Session session = currentUser.getSession();  //获取当前用户的session       如何获取的可以百度去查找Suject和session的关系和用法
        session.setAttribute(Const.SESSION_SECURITY_CODE, code);            //将当前随机4位字符写入session,目的是为了在前台验证的时候用
        
        try {
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);      //  将验证码写到前端
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private String drawImg(ByteArrayOutputStream output){
        String code = "";
        for(int i=0; i<4; i++){
            code += randomChar();

        }

        //获取四位随机字符

        int width = 70;
        int height = 25;
        BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);   //创建一个图片对象
        Font font = new Font("Times New Roman",Font.PLAIN,20);     //创建文字对象,可以在此处改变显示的验证码字符字体和大小
        Graphics2D g = bi.createGraphics();   //创建bi的画笔对象,用来将4位随机数画入bi中
        g.setFont(font);  //设置画笔的字体
        Color color = new Color(66,2,82);   //创建颜色对象并赋予颜色,当然也可以自己创建一个随机颜色对象,具体实现方法就不在此展现了
        g.setColor(color); //设置字符颜色
        g.setBackground(new Color(226,226,240));  //设置画布背景色
        g.clearRect(0, 0, width, height);    //先擦除面板
        FontRenderContext context = g.getFontRenderContext();   // 获取字体的像素范围对象
        Rectangle2D bounds = font.getStringBounds(code, context);    //创建矩形对象并写入4位随机字符和设定字体像素
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;   //计算好g组件的中间位置
        g.drawString(code, (int)x, (int)baseY);   //将4位随机字符写入bi对象中
        g.dispose();   //释放g的资源
        try {
            ImageIO.write(bi, "jpg", output);   //将bi写入output字节组流中,后缀加上jpg格式图片
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;   //返回4位随机字符,验证用
    }
    //随机字符生成方法
    private char randomChar(){
        Random r = new Random();
        String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
        return s.charAt(r.nextInt(s.length()));
    }

2.前台代码

html:

<div style="float: left;" class="codediv">
            <input type="text" name="code" id="code" class="login_code"
            style="height:16px; padding-top:4px;" />
</div>
<div style="float: left;">
           <i><img style="height:22px;" id="codeImg" alt="点击更换"
               title="点击更换" src="" />

          </i>
 </div>

js:

$(document).ready(function() {
            changeCode();  //进来加载一遍验证码
            $("#codeImg").bind("click", changeCode);  //点击图片重新加载
});

function genTimestamp() {
            var time = new Date();
            return time.getTime();
}

function changeCode() {
            $("#codeImg").attr("src", "code.do?t=" + genTimestamp());     //ssm框架调用方式,可以修改成自己的调用方式
}

猜你喜欢

转载自blog.csdn.net/qq904748592/article/details/52671355