1.工具类,生成随机验证码字符串

import java.util.Arrays;

/**
* 工具类,生成随机验证码字符串
*
* @version 1.0
* @author
*
*/ 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);
}
public static void main(String[] args) {
SecurityCode code = new SecurityCode();
System.out.println(getSecurityCode(6,SecurityCodeLevel.Hard,false));
}
}

2.

package code;

import com.opensymphony.xwork2.ActionSupport;
import java.io.ByteArrayInputStream;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware; /**
* 提供图片验证码
* @version 1.0 2012/08/22
* @author dongliyang
*/
@SuppressWarnings("serial")
public class SecurityCodeImageAction extends ActionSupport implements SessionAware{ //Struts2中Map类型的session
private Map<String, Object> session; //图片流
private ByteArrayInputStream imageStream; public ByteArrayInputStream getImageStream() {
return imageStream;
} public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
} public String execute() throws Exception {
//如果开启Hard模式,可以不区分大小写
// String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase(); //获取默认难度和长度的验证码
String securityCode = SecurityCode.getSecurityCode();
imageStream = SecurityImage.getImageAsInputStream(securityCode);
//放入session中
session.put("SESSION_SECURITY_CODE", securityCode);
return SUCCESS;
} public void setSession(Map<String, Object> session) {
this.session = session;
} }

3.

package code;

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; /**
* 工具类,生成验证码图片
* @version 1.0 2012/08/21
* @author dongliyang
*
*/
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;
}
}

4.

package code;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class CodeAction extends ActionSupport{
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session=request.getSession();
HttpServletResponse response = ServletActionContext.getResponse();
public String execute(){ try {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String validateC = (String) request.getSession().getAttribute("SESSION_SECURITY_CODE");
System.out.println("validateC"+validateC);
String veryCode = request.getParameter("code");
System.out.println("c"+veryCode);
PrintWriter out;
out = response.getWriter();
if(veryCode==null||"".equals(veryCode)){
//response.sendRedirect(refer);
out.print("验证码不能为空");
System.out.println("验证码不能为空");
} else{
if(validateC.equals(veryCode)){ out.print("验证码正确");
//request.getRequestDispatcher("ServletTo").forward(request, response);
System.out.println("验证码正确");
}else{ out.print("验证码错误");
System.out.println("验证码错误");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

Java工具类-验证码工具的更多相关文章

  1. Java容器类Collection,List,Set,Map.,Iterator,Collections工具类,Arrays工具类,Comparable

    Java容器类Collection,List,Set,Map.,Iterator,Collections工具类,Arrays工具类,Comparable接口,泛型 Collection,List,Se ...

  2. java 工具类 验证码

    第一步: 引入工具类 工具类一: import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import jav ...

  3. JAVA短信验证码 工具类

    MsgCodeUtil.java package com.hg.util; import com.soyea.enums.ResultEnum; import com.soyea.exception. ...

  4. java工具类-日期工具类

    1.获得时间戳 为了统一其他语言的如php和unix系统获取的时间戳是10位长度的,精确到秒. java时间戳长度是13位,精确到毫秒 我们获取时间戳需要相应处理. //获取当前时间戳,除以1000, ...

  5. Java常用工具类---IP工具类、File文件工具类

    package com.jarvis.base.util; import java.io.IOException;import java.io.InputStreamReader;import jav ...

  6. Java常用工具类---XML工具类、数据验证工具类

    package com.jarvis.base.util; import java.io.File;import java.io.FileWriter;import java.io.IOExcepti ...

  7. 工具类 分页工具类PageParamBean

    自己编写的分页工具类,根据不同的数据库类型,生成对应的分页sql信息,分享给大家,希望大家共勉,工具类有些地方,大家可能不需要,请根绝自己的需要进行修改使用,核心逻辑都在,如果大家觉得有什么不妥,欢迎 ...

  8. 工具类与工具函数 —— NextPrime

    求大于某数的下一个素数: static int NextPrime (int N) { if (N % 2 == 0) ++N; int i; for (; ; N += 2){ for (i = 3 ...

  9. Python 工具类与工具函数 —— pair

    def pair(lis): n = len(lis) for i in range(n): for j in range(i+1, n): yield lis[i], lis[j] 这样在调用端,访 ...

随机推荐

  1. [Leetcode] LRU 算法实现

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  2. 51Nod 1344 走格子 | 贪心

    Input示例 5 1 -2 -1 3 4 Output示例 2 贪心 #include <bits/stdc++.h> using namespace std; typedef long ...

  3. 51Nod 1003 阶乘后面0的数量 | 思维

    题意:n的阶乘后面0的个数,如果直接算出阶乘再数0的数量一定会超时的. 因为10=2*5,所以求出5贡献的次数就行. #include "bits/stdc++.h" using ...

  4. 数据结构:K-D树

    K-D树实际上是一棵高维二叉搜索树,与普通二叉搜索树不同的是,树中存储的是一些K维数据 普通的二叉搜索树是一维的,当推广到K维后,就是我们的K-D树了 在K-D树中跟二叉搜索树差不多,也是将一个K维的 ...

  5. [洛谷P2571] [SCOI2010]传送带

    题目描述 在一个2维平面上有两条传送带,每一条传送带可以看成是一条线段.两条传送带分别为线段AB和线段CD.lxhgww在AB上的移动速度为P,在CD上的移动速度为Q,在平面上的移动速度R.现在lxh ...

  6. web开发中防止SQL注入

    一.SQL注入简介 SQL注入是比较常见的网络攻击方式之一,它不是利用操作系统的BUG来实现攻击,而是针对程序员编写时的疏忽,通过SQL语句,实现无账号登录,甚至篡改数据库. 二.SQL注入攻击的总体 ...

  7. 要back的题目 先立一个flag

    要back的题目 目标是全绿!back一题删一题! acmm7 1003 1004 acmm8 1003 1004 sysu20181013 Stat Origin Title Solved A Gy ...

  8. JS语句循环(100以内奇偶数、100以内与7先关的数、100以内整数的和、10以内阶乘、乘法口诀、篮球弹起高度、64格子放东西)

    3.循环 循环是操作某一个功能(执行某段代码). ①循环四要素: a 循环初始值 b 循环的条件 c 循环状态 d 循环体 ②for循环 a 穷举:把所有的可能性的都一一列出来. b 迭代:每次循环都 ...

  9. bzoj 2434 fail tree+dfs序

    首先比较明显的是我们可以将字符串组建立ac自动机,那么对于询问s1字符串在s2字符串中出现的次数,就是在以s1结尾为根的fail tree中,子树有多少个节点是s2的节点,这样我们处理fail tre ...

  10. linux下守护进程的创建

    最近在学习linux c编程 看到了守护进程的创建,感觉很好玩, 测试环境ubuntu 15.04 下面贴出测试代码 #include <stdio.h> #include <std ...