import java.util.Arrays;
/**
* 工具类,生成随机验证码字符串
* @version 1.0 2012/12/01
* @author shiyz
*
*/
public class SecurityCode {
/**
* 验证码难度级别,Simple只包含数字,Medium包含数字和小写英文,Hard包含数字和大小写英文
*/
public enum SecurityCodeLevel {Simple,Medium,Hard}; /**
* 产生默认验证码,4位中等难度
* @return String 验证码
*/
public static String getSecurityCode(){
return getSecurityCode(4,SecurityCodeLevel.Medium,false);
}
/**
* 产生长度和难度任意的验证码
* @param length 长度
* @param level 难度级别
* @param isCanRepeat 是否能够出现重复的字符,如果为true,则可能出现 5578这样包含两个5,如果为false,则不可能出现这种情况
* @return String 验证码
*/
public static String getSecurityCode(int length,SecurityCodeLevel level,boolean isCanRepeat){
//随机抽取len个字符
int len=length; //字符集合(除去易混淆的数字0、数字1、字母l、字母o、字母O)
char[] codes={'1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'}; //根据不同的难度截取字符数组
if(level==SecurityCodeLevel.Simple){
codes=Arrays.copyOfRange(codes, 0,9);
}else if(level==SecurityCodeLevel.Medium){
codes=Arrays.copyOfRange(codes, 0,33);
}
//字符集合长度
int n=codes.length; //抛出运行时异常
if(len>n&&isCanRepeat==false){
throw new RuntimeException(
String.format("调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常,当isCanRepeat为%3$s时,传入参数%1$s不能大于%4$s",
len,level,isCanRepeat,n));
}
//存放抽取出来的字符
char[] result=new char[len];
//判断能否出现重复的字符
if(isCanRepeat){
for(int i=0;i<result.length;i++){
//索引 0 and n-1
int r=(int)(Math.random()*n); //将result中的第i个元素设置为codes[r]存放的数值
result[i]=codes[r];
}
}else{
for(int i=0;i<result.length;i++){
//索引 0 and n-1
int r=(int)(Math.random()*n); //将result中的第i个元素设置为codes[r]存放的数值
result[i]=codes[r]; //必须确保不会再次抽取到那个字符,因为所有抽取的字符必须不相同。
//因此,这里用数组中的最后一个字符改写codes[r],并将n减1
codes[r]=codes[n-1];
n--;
}
}
return String.valueOf(result);
}
}
 import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 验证码生成器类,可生成数字、大写、小写字母及三者混合类型的验证码。
* 支持自定义验证码字符数量;
* 支持自定义验证码图片的大小;
* 支持自定义需排除的特殊字符;
* 支持自定义干扰线的数量;
* 支持自定义验证码图文颜色
* @author shiyz
* @version 1.0
*/
public class SecurityImage {
/**
* 生成验证码图片
* @param securityCode 验证码字符
* @return BufferedImage 图片
*/
public static BufferedImage createImage(String securityCode){
//验证码长度
int codeLength=securityCode.length();
//字体大小
int fSize = 15;
int fWidth = fSize + 1;
//图片宽度
int width = codeLength * fWidth + 6 ;
//图片高度
int height = fSize * 2 + 1;
//图片
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g=image.createGraphics();
//设置背景色
g.setColor(Color.WHITE);
//填充背景
g.fillRect(0, 0, width, height);
//设置边框颜色
g.setColor(Color.LIGHT_GRAY);
//边框字体样式
g.setFont(new Font("Arial", Font.BOLD, height - 2));
//绘制边框
g.drawRect(0, 0, width - 1, height -1);
//绘制噪点
Random rand = new Random();
//设置噪点颜色
g.setColor(Color.LIGHT_GRAY);
for(int i = 0;i < codeLength * 6;i++){
int x = rand.nextInt(width);
int y = rand.nextInt(height);
//绘制1*1大小的矩形
g.drawRect(x, y, 1, 1);
}
//绘制验证码
int codeY = height - 10;
//设置字体颜色和样式
g.setColor(new Color(19,148,246));
g.setFont(new Font("Georgia", Font.BOLD, fSize));
for(int i = 0; i < codeLength;i++){
g.drawString(String.valueOf(securityCode.charAt(i)), i * 16 + 5, codeY);
}
//关闭资源
g.dispose();
return image;
}
/**
* 返回验证码图片的流格式
* @param securityCode 验证码
* @return ByteArrayInputStream 图片流
*/
public static ByteArrayInputStream getImageAsInputStream(String securityCode){
BufferedImage image = createImage(securityCode);
return convertImageToStream(image);
}
/**
* 将BufferedImage转换成ByteArrayInputStream
* @param image 图片
* @return ByteArrayInputStream 流
*/
private static ByteArrayInputStream convertImageToStream(BufferedImage image){
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
try {
jpeg.encode(image);
byte[] bts = bos.toByteArray();
inputStream = new ByteArrayInputStream(bts);
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}
 private ByteArrayInputStream imageStream; 

     public String makePictureCode() throws Exception{
//String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase(); //获取默认难度和长度的验证码
String securityCode = SecurityCode.getSecurityCode();
imageStream = SecurityImage.getImageAsInputStream(securityCode);
//放入session中
ServletActionContext.getRequest().getSession().setAttribute("securityCode", securityCode);
return "success"; }
public ByteArrayInputStream getImageStream() {
return imageStream;
} public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}

struts2 xml配置:

   <result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
<param name="bufferSize">2048</param>
</result>

界面:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>IdentifyingCode page</title>
<script type="text/javascript">
function myReload(){
document.getElementById("createCheckCode").src=document.getElementById("createCheckCode").src + "?nocache="+new Date().getTime();
}
</script>
</head> <body>

效果:

这样一个验证码的功能就可以使用了...

struts2结合生成验证码的更多相关文章

  1. 动态生成验证码———MVC版

    上面有篇博客也是写的验证码,但那个是适用于asp.net网站的. 今天想在MVC中实现验证码功能,弄了好久,最后还是看博友文章解决的,感谢那位博友. 首先引入生成验证码帮助类. ValidateCod ...

  2. laravel 生成验证码的方法

    在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用.下面我们就来介绍下使用细节: 首先, composer.j ...

  3. java web学习总结(九) -------------------通过Servlet生成验证码图片

    一.BufferedImage类介绍 生成验证码图片主要用到了一个BufferedImage类,如下:

  4. android 生成验证码图片

    (转自:http://blog.csdn.net/onlyonecoder/article/details/8231373) package com.nobeg.util; import java.u ...

  5. PHP 动态生成验证码

    ……机器人会在网站中搜寻允许他们插入广告的输入表单,在虚拟世界没有什么能阻挡它们胡作非为.这些机器人效率极高,完全不关心所攻击的表单的本来用途.它们唯一的目标就是用它们的垃圾广告覆盖你的内容,残忍地为 ...

  6. PHP生成验证码及单实例应用

    /* note: * this 指向当前对象本身 * self 指向当前类 * parent 指向父类 */ /* 验证码工具类 * @author pandancode * @date 20150- ...

  7. ASP.NET ashx实现无刷新页面生成验证码

    现在大部分网站登陆时都会要求输入验证码,在网上也看了一些范例,现在总结一下如何实现无刷新页面生成验证码. 效果图: 实现方式: 前台: <div> <span>Identify ...

  8. PHP-仿ecshop生成验证码

    <?php /* 生成验证码 */ // 1.创建画布(基于已有图像) $n = mt_rand(1,5); $im = imagecreatefromjpeg('./images/captch ...

  9. Java生成验证码原理(jsp)

     验证码的作用: 验证码是Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的 ...

随机推荐

  1. sublime text 3快捷键设置

    sublime text 3  v-3103默认快捷键设置 [ { "keys": ["ctrl+shift+n"], "command": ...

  2. 20160410javaweb之JDBC---DBUtils框架

    DBUtils 1.DbUtils 工具类 2.QueryRunner -- 两行代码搞定增删改查 (1)QueryRunner() --需要控制事务时,使用这组方法 int update(Conne ...

  3. HttpServlet was not found on the Java

    今天新建jsp时出现了一个错误,如下图 分析:应该是没有找到相关jar包 解决方案: 如图: 这回就没错了

  4. 使用PDO持久化连接

    无论是何种编程语言,几乎都要经常与各种数据库打交道.不过,众所周知的是,在程序与数据库之间建立连接是一件比较耗费资源的事情,因此编程技术领域的许多专家.前辈们就设想并提出了各种解决方案,以减少不必要的 ...

  5. aptitude

    aptitude比apt-get 要好用.是 Debian 及其衍生系统中功能极其强大的包管理工具.与 apt-get 不同的是,aptitude在处理依赖问题上更佳一些.举例来说,aptitude在 ...

  6. linux mysql目录详解

    1.mysql数据库目录 /var/lib/mysql 2.mysql配置文件目录 /usr/share/mysql 3.相关命令目录 /usr/bin 4.启动脚本目录

  7. iOS 项目中将 http 改成 https 后需要改动的地方(密钥验证)

    这种是不验证证书的密钥 AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone] ...

  8. Installshield: custom action return value

    参考:MSDN: Custom Action Return Values 参考:MSDN: Logging of Action Return Values

  9. PAT 1065 A+B and C (64bit) (20)

    1065. A+B and C (64bit) (20) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 HOU, Qiming G ...

  10. php 接收二进制流转换成图片

    php 接收二进制流转换成图片,图片类imageUpload.php如下: <?php /** * 图片类 * @author http://blog.csdn.net/haiqiao_2010 ...