记录struts2 和struts1的页面验证码生成
2016-06-06 14:49
495 查看
记录struts2 和struts1的页面验证码生成
Struts1,参考路径http://bbs.csdn.net/topics/330130479
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class SecureImg {
private String sRand = "";
public Color getRandColor(int fc, int bc)
{//给定范围获得随机颜色
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
public BufferedImage creatImage()
{
// 在内存中创建图象
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
//生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
//设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
//画边框
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(4位数字)
//String rand = request.getParameter("rand");
//rand = rand.substring(0,rand.indexOf("."));
for (int i = 0; i < 4; i++)
{
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 6, 16);
}
// 图象生效
g.dispose();
return image;
}
public String getSRand()
{
return sRand;
}
public void setSRand(String rand)
{
sRand = rand;
}
}
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.socool.entity.SecureImg;
public class SecureImgAction extends Action {
@SuppressWarnings("unused")
private static final String TAG = "SecureImgAction";
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setHeader("P3P", "CP=CAO PSA OUR");
response.setDateHeader("Expires", 0);
HttpSession session=request.getSession();
SecureImg imageCode=new SecureImg();
try {
ImageIO.write(imageCode.creatImage(), "JPEG", response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setAttribute("CheckCode",imageCode.getSRand());
return null;
}
}
<img src="secureimg.do" id="checkimg" /><a href="javascript:onclick=changeImg()" id="changeImg">看不清,换一张</a>
<script type="text/javascript">
function changeImg(){
document.getElementById("checkimg").src="secureimg.do?timestamp=" + new Date().getTime();
}
</script>
struts2 参考路径忘了
import java.io.ByteArrayInputStream;
import java.util.Map;
import net.singlex.common.SecurityCode;
import net.singlex.common.SecurityImage;
import net.singlex.common.SecurityCode.SecurityCodeLevel;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class SecurityCodeImageAction extends ActionSupport implements
SessionAware {
private Map<String, Object> session;
private ByteArrayInputStream imageStream;
@Override
public String execute() throws Exception {
//如果开启Hard模式,可不区分大小写
String securityCode = SecurityCode.getSecurityCode(6, SecurityCodeLevel.Hard, false);
//获取默认难度和长度的验证码
// String securityCode = SecurityCode.getSecurityCode();
imageStream = SecurityImage.getImageAsInputStream(securityCode);
//放入session
session.put("securityCode", securityCode);
return SUCCESS;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}
public ByteArrayInputStream getImageStream() {
return imageStream;
}
}
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.util.Random;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 工具类,生成验证码图片
* @author SingleX SingleXer@Gmail.com
* @version 1.0 2013-8-27 上午09:01:16
*/
public class SecurityImage {
/**
* 生成验证码图片
* @param securityCode
* @return
*/
public static BufferedImage createImage(String securityCode){
int codeLength = securityCode.length();//验证码长度
int fontSize = 15;//字体大小
int fontWidth = fontSize+1;
//图片宽高
int width = codeLength*fontWidth+6;
int height = fontSize*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);
g.drawRect(x, y, 1, 1);//绘制1*1大小的矩形
}
//绘制验证码
int codeY = height-10;
g.setColor(new Color(19,148,246));
g.setFont(new Font("Georgia", Font.BOLD, fontSize));
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
*/
public static ByteArrayInputStream getImageAsInputStream(String securityCode){
BufferedImage image = createImage(securityCode);
return convertImageToStream(image);
}
/**
* 将BufferedImage转换成ByteArrayinputStream
* @param image
* @return
*/
public static ByteArrayInputStream convertImageToStream(BufferedImage image){
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
try {
encoder.encode(image);
byte[] b = outStream.toByteArray();
inputStream = new ByteArrayInputStream(b);
} catch (Exception e) {
}
return inputStream;
}
}
import java.util.Arrays;
/**
* 工具类,生成随机验证码字符串
*
* @author SingleX SingleXer@gmail.com
* @version 1.0 2013-8-26 上午10:00:15
*/
public class SecurityCode {
/**
* 验证码难度级别 Simple-数字 Medium-数字和小写字母 Hard-数字和大小写字母
*/
public enum SecurityCodeLevel {
Simple, Medium, Hard
};
/**
* 产生默认验证码,4位中等难度
*
* @return
*/
public String getSecurityCode() {
return getSecurityCode(4, SecurityCodeLevel.Medium, false);
}
/**
* 产生长度和难度任意的验证码
*
* @param length
* @param level
* @param isCanRepeat
* @return
*/
public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
// 随机抽取len个字符
int len = length;
// 字符集合(--除去易混淆的数字0,1,字母l,o,O)
char[] codes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', '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', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
// 根据不同难度截取字符串
if (level == SecurityCodeLevel.Simple) {
codes = Arrays.copyOfRange(codes, 0, 10);
} else if (level == SecurityCodeLevel.Medium) {
codes = Arrays.copyOfRange(codes, 0, 36);
}
// 字符集和长度
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个元素设置为code[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个元素设置为code[r]存放的数值
result[i] = codes[r];
// 必须确保不会再次抽取到那个字符,这里用数组中最后一个字符改写code[r],并将n-1
codes[r] = codes[n - 1];
n--;
}
}
return String.valueOf(result);
}
}
<action name="SecurityCodeImageAction" class="com.web.SecurityCodeImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
<param name="bufferSize">2048</param>
</result>
</action>
<tr>
<td><img src="Security/SecurityCodeImageAction" id="verify" style="cursor:hand;" alt="看不清,换一张" /></td>
<td><a href="javascript:onclick=changeImg()" id="changeImg">看不清,换一张</a></td>
</tr>
struts1的验证码实现样式可根据struts2的部分做修改。没细分
Struts1,参考路径http://bbs.csdn.net/topics/330130479
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class SecureImg {
private String sRand = "";
public Color getRandColor(int fc, int bc)
{//给定范围获得随机颜色
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
public BufferedImage creatImage()
{
// 在内存中创建图象
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
//生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
//设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
//画边框
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(4位数字)
//String rand = request.getParameter("rand");
//rand = rand.substring(0,rand.indexOf("."));
for (int i = 0; i < 4; i++)
{
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 6, 16);
}
// 图象生效
g.dispose();
return image;
}
public String getSRand()
{
return sRand;
}
public void setSRand(String rand)
{
sRand = rand;
}
}
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.socool.entity.SecureImg;
public class SecureImgAction extends Action {
@SuppressWarnings("unused")
private static final String TAG = "SecureImgAction";
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setHeader("P3P", "CP=CAO PSA OUR");
response.setDateHeader("Expires", 0);
HttpSession session=request.getSession();
SecureImg imageCode=new SecureImg();
try {
ImageIO.write(imageCode.creatImage(), "JPEG", response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setAttribute("CheckCode",imageCode.getSRand());
return null;
}
}
<img src="secureimg.do" id="checkimg" /><a href="javascript:onclick=changeImg()" id="changeImg">看不清,换一张</a>
<script type="text/javascript">
function changeImg(){
document.getElementById("checkimg").src="secureimg.do?timestamp=" + new Date().getTime();
}
</script>
struts2 参考路径忘了
import java.io.ByteArrayInputStream;
import java.util.Map;
import net.singlex.common.SecurityCode;
import net.singlex.common.SecurityImage;
import net.singlex.common.SecurityCode.SecurityCodeLevel;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class SecurityCodeImageAction extends ActionSupport implements
SessionAware {
private Map<String, Object> session;
private ByteArrayInputStream imageStream;
@Override
public String execute() throws Exception {
//如果开启Hard模式,可不区分大小写
String securityCode = SecurityCode.getSecurityCode(6, SecurityCodeLevel.Hard, false);
//获取默认难度和长度的验证码
// String securityCode = SecurityCode.getSecurityCode();
imageStream = SecurityImage.getImageAsInputStream(securityCode);
//放入session
session.put("securityCode", securityCode);
return SUCCESS;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}
public ByteArrayInputStream getImageStream() {
return imageStream;
}
}
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.util.Random;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 工具类,生成验证码图片
* @author SingleX SingleXer@Gmail.com
* @version 1.0 2013-8-27 上午09:01:16
*/
public class SecurityImage {
/**
* 生成验证码图片
* @param securityCode
* @return
*/
public static BufferedImage createImage(String securityCode){
int codeLength = securityCode.length();//验证码长度
int fontSize = 15;//字体大小
int fontWidth = fontSize+1;
//图片宽高
int width = codeLength*fontWidth+6;
int height = fontSize*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);
g.drawRect(x, y, 1, 1);//绘制1*1大小的矩形
}
//绘制验证码
int codeY = height-10;
g.setColor(new Color(19,148,246));
g.setFont(new Font("Georgia", Font.BOLD, fontSize));
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
*/
public static ByteArrayInputStream getImageAsInputStream(String securityCode){
BufferedImage image = createImage(securityCode);
return convertImageToStream(image);
}
/**
* 将BufferedImage转换成ByteArrayinputStream
* @param image
* @return
*/
public static ByteArrayInputStream convertImageToStream(BufferedImage image){
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
try {
encoder.encode(image);
byte[] b = outStream.toByteArray();
inputStream = new ByteArrayInputStream(b);
} catch (Exception e) {
}
return inputStream;
}
}
import java.util.Arrays;
/**
* 工具类,生成随机验证码字符串
*
* @author SingleX SingleXer@gmail.com
* @version 1.0 2013-8-26 上午10:00:15
*/
public class SecurityCode {
/**
* 验证码难度级别 Simple-数字 Medium-数字和小写字母 Hard-数字和大小写字母
*/
public enum SecurityCodeLevel {
Simple, Medium, Hard
};
/**
* 产生默认验证码,4位中等难度
*
* @return
*/
public String getSecurityCode() {
return getSecurityCode(4, SecurityCodeLevel.Medium, false);
}
/**
* 产生长度和难度任意的验证码
*
* @param length
* @param level
* @param isCanRepeat
* @return
*/
public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
// 随机抽取len个字符
int len = length;
// 字符集合(--除去易混淆的数字0,1,字母l,o,O)
char[] codes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', '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', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
// 根据不同难度截取字符串
if (level == SecurityCodeLevel.Simple) {
codes = Arrays.copyOfRange(codes, 0, 10);
} else if (level == SecurityCodeLevel.Medium) {
codes = Arrays.copyOfRange(codes, 0, 36);
}
// 字符集和长度
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个元素设置为code[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个元素设置为code[r]存放的数值
result[i] = codes[r];
// 必须确保不会再次抽取到那个字符,这里用数组中最后一个字符改写code[r],并将n-1
codes[r] = codes[n - 1];
n--;
}
}
return String.valueOf(result);
}
}
<action name="SecurityCodeImageAction" class="com.web.SecurityCodeImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
<param name="bufferSize">2048</param>
</result>
</action>
<tr>
<td><img src="Security/SecurityCodeImageAction" id="verify" style="cursor:hand;" alt="看不清,换一张" /></td>
<td><a href="javascript:onclick=changeImg()" id="changeImg">看不清,换一张</a></td>
</tr>
struts1的验证码实现样式可根据struts2的部分做修改。没细分
相关文章推荐
- JAVA中List的几个方法
- [框架整合]spring+springmvc+mybatis(1)
- 3、spring_aop
- 什么是Java中的内存泄露
- java中的锁
- Spring 给Bean属性注入null值
- pojo和javabean的比较
- 在eclipse如何删除无效的maven build
- Java是如何管理内存
- 2、spring_ioc
- springmvc
- Ubuntu 16.04 火狐添加java插件、解决Firefox强制低版本java插件运行以及安全设置限制自签名应用程序运行
- Spring Boot的Profile切换方式
- 用spring的InitializingBean的afterPropertiesSet来初始化
- 栈与堆的区别
- Spring AOP时的问题
- [LeetCode][6]ZigZag Conversion解析与特殊解法 -Java实现
- Spring AOP 学习(一) 代理模式
- Java泛型
- java中Scanner的hasNext()的疑问