一个简单的随机验证码生成程序

封装了一个简单的随机生成验证码的类,为以后做自己的网站做准备。做了一个demo,需要的同学可以拿去用。

package xyz.jison.verificationcode.service;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import xyz.jison.verificationcode.model.VerificationCodeModel;

/**
* 生成图形验证码
* @author jison
* @since 2015-8-13
* @version 1.0
*
*/
public class VerificationCode {

public VerificationCode(VerificationCodeModel model){
this.model = model;
}

/**
* 验证码的model
*/
private VerificationCodeModel model;

/**
* 记录验证码的字符串形式
*/
private StringBuffer verificationCodeStr = new StringBuffer();

/**
* 记录验证码的图片形式
*/
private BufferedImage verificationCodeImage;

/**
* 根据以下顺序绘制验证码,边框--》验证码--》干扰线,后绘制的覆盖先绘制的
* @return
*/
public VerificationCode generateVerifitionCode(){
verificationCodeImage = new BufferedImage(model.getWidth(), model.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = verificationCodeImage.getGraphics();
paintBorder(g);
paintVerificationCode(g);
paintInterferingLine(g);
return this;
}

/**
* 绘制验证码干扰线
* @param g
*/
private void paintInterferingLine(Graphics g){
Random random = new Random();
for (int i = 0; i < model.getInterferingLineNum(); i++) {
g.setColor(getRandomColor());
g.drawLine(random.nextInt(model.getWidth()),
random.nextInt(model.getHeight()),
random.nextInt(model.getWidth()),
random.nextInt(model.getHeight()));
}
}

/**
* 绘制验证码
* @param g
*/
private void paintVerificationCode(Graphics g){
Random random = new Random();
g.setFont(model.getFont());
for (int i = 0; i < model.getVerificationCodeNum(); i++) {
g.setColor(getRandomColor());
int codeLocate = random.nextInt(model.getVerificationCodeScope());
String paintStr = model.getMetadata().substring(codeLocate, codeLocate+1);
g.drawString(paintStr,
model.getPaddingLeft() + model.getBeginPaintX()*i,
model.getBeginPaintY());
// 记录验证码中的字符
verificationCodeStr.append(paintStr);
}
}

/**
* 绘制边框
* @param g
*/
private void paintBorder(Graphics g){
g.setColor(model.getBorderColor());
g.fillRect(0, 0, model.getWidth(), model.getHeight());
g.setColor(model.getBackgroundColor());
int borderSize = model.getBorderSize();
g.fillRect(borderSize, borderSize, model.getWidth() - (borderSize<<1), model.getHeight() - (borderSize<<1));
}

/**
*
* @return Color 随机生成RGB颜色
*/
private Color getRandomColor(){
Random random = new Random();
Color color = new Color(random.nextInt(model.getColorScope()),
random.nextInt(model.getColorScope()),
random.nextInt(model.getColorScope()));
return color;
}

public StringBuffer getVerificationCodeStr() {
return verificationCodeStr;
}

public BufferedImage getVerificationCodeImage() {
return verificationCodeImage;
}

}



package xyz.jison.verificationcode.model;

import java.awt.Color;
import java.awt.Font;
import java.io.Serializable;

/**
* 验证码相关的属性
* @author jison
* @since 2015-8-13
* @version 1.0
*
*/
public class VerificationCodeModel implements Serializable{

private static final long serialVersionUID = 1L;

/**
* 验证码的元数据,默认为所有字母大小写加数字
*/
private String metadata = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

/**
* 验证码的随机数取值范围,验证码元数据的长度
*/
private int verificationCodeScope = metadata.length();

/**
* 验证码的位数,默认为4位数
*/
private int verificationCodeNum = 4;

/**
* 验证码的干扰线的条数,默认为10条
*/
private int interferingLineNum = 10;

/**
* 验证码图片的宽度,默认为80px
*/
private int width = 80;

/**
* 验证码图片的高度,默认为40px;
*/
private int height = 40;

/**
* 验证码的字体,默认为宋体,粗体,30px
*/
private Font font = new Font("宋体", Font.BOLD, 30);

/**
* 颜色的随机数取值范围,默认为255
*/
private int colorScope = 255;

/**
* 边框颜色,默认为黑色
*/
private Color borderColor = Color.BLACK;

/**
* 背景颜色,默认为白色
*/
private Color backgroundColor = Color.WHITE;

/**
* 边框大小,默认为1
*/
private int borderSize = 1;

/**
* 验证码的左边距,默认为0
*/
private int paddingLeft = 0;

/**
* 起始绘制验证码的X坐标,默认为20
*/
private int beginPaintX = 20;

/**
* 起始绘制验证码的Y坐标,默认为30
*/
private int beginPaintY = 30;

public String getMetadata() {
return metadata;
}

public void setMetadata(String metadata) {
this.metadata = metadata;
}

public int getVerificationCodeScope() {
return verificationCodeScope;
}

public void setVerificationCodeScope(int verificationCodeScope) {
this.verificationCodeScope = verificationCodeScope;
}

public int getVerificationCodeNum() {
return verificationCodeNum;
}

public void setVerificationCodeNum(int verificationCodeNum) {
this.verificationCodeNum = verificationCodeNum;
}

public int getInterferingLineNum() {
return interferingLineNum;
}

public void setInterferingLineNum(int interferingLineNum) {
this.interferingLineNum = interferingLineNum;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public Font getFont() {
return font;
}

public void setFont(Font font) {
this.font = font;
}

public int getColorScope() {
return colorScope;
}

public void setColorScope(int colorScope) {
this.colorScope = colorScope;
}

public Color getBorderColor() {
return borderColor;
}

public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}

public Color getBackgroundColor() {
return backgroundColor;
}

public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}

public int getBorderSize() {
return borderSize;
}

public void setBorderSize(int borderSize) {
this.borderSize = borderSize;
}

public int getPaddingLeft() {
return paddingLeft;
}

public void setPaddingLeft(int paddingLeft) {
this.paddingLeft = paddingLeft;
}

public int getBeginPaintX() {
return beginPaintX;
}

public void setBeginPaintX(int beginPaintX) {
this.beginPaintX = beginPaintX;
}

public int getBeginPaintY() {
return beginPaintY;
}

public void setBeginPaintY(int beginPaintY) {
this.beginPaintY = beginPaintY;
}

}



package xyz.jison.verificationcode.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
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 xyz.jison.verificationcode.model.VerificationCodeModel;
import xyz.jison.verificationcode.service.VerificationCode;

/**
* 生成验证码的Servlet
* @author jison
* @since 2015-8-13
* @version 1.0
*
*/
@WebServlet(urlPatterns="/verificationCodeServlet")
public class VerificationCodeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("image/jpeg");
OutputStream outputStream = resp.getOutputStream();
VerificationCode verificationCode = new VerificationCode(new VerificationCodeModel());
verificationCode = verificationCode.generateVerifitionCode();
BufferedImage verificationCodeImage = verificationCode.getVerificationCodeImage();
String verificationCodeStr = verificationCode.getVerificationCodeStr().toString();
req.getSession().setAttribute("verificationCodeStr", verificationCodeStr);
ImageIO.write(verificationCodeImage, "jpg", outputStream);
}


}



package xyz.jison.verificationcode.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 验证验证码是否正确Servlet
* @author jison
* @since 2015-8-13
* @version 1.0
*
*/
@WebServlet(urlPatterns="/validateServlet")
public class ValidateServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String verificationCodeStr = (String)req.getSession().getAttribute("verificationCodeStr");
String userInputCode = req.getParameter("userInputCode");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
if(verificationCodeStr!=null){
if(userInputCode.equalsIgnoreCase(verificationCodeStr)){
out.append("验证通过!");
} else {
out.append("验证码错误!");
}
req.getSession().removeAttribute("verificationCodeStr");
}else {
out.append("验证码失效!");
}
}
}



<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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">
<title>验证码</title>
<script type="text/javascript">
var xmlhttp=null;
function updateCode(){
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById("code").src = "verificationCodeServlet?" + new Date();
}
else
{
alert("验证码刷新失败:" + xmlhttp.statusText);
}
}
}
xmlhttp.open("POST", "verificationCodeServlet" , true);
xmlhttp.send(null);
}
else
{
alert("浏览器不支持ajax!");
}
}
</script>
</head>
<body>
<form action="validateServlet" method="post">
<input name="userInputCode" type="text" />
<img id="code" src="verificationCodeServlet" />
[url=#]看不清,换一张[/url]<br/>
<input type="submit" value="验证" />
</form>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值