java验证码

来源:互联网 发布:龙华淘宝电商 编辑:程序博客网 时间:2024/06/03 18:05

jsp页面代码:

<input type="text"  id="code_img" name="code_img" value="">
<input type="hidden" name="captcha" id="captcha" />
<p><img src="${ctx}/captcha.shtml" id="code_img_area" style="width:80px;height:27px;float:left;cursor:pointer; "
alt="验证码" title="验证码" onclick="changeImg();" /></p>

js代码:
var codeImg = $("#code_img").val();
var result= $.ajax({
type : "post",
cache: false,
async:false,
url: ctx+"/checkCaptcha.shtml"
}).responseText;

if($.trim(result) != $.trim($('#code_img').val().toUpperCase())){
$('#code_img_area').attr('src',ctx+'/captcha.shtml?t='+(new Date().getTime()));
layer.msg("验证码错误", function(){});
  return false;
}else{
$("#captcha").val($('#code_img').val().toUpperCase());
}
function changeImg() {
$("#code_img_area").attr('src',ctx+"/captcha.shtml?t="+(new Date().getTime()));
return false;
}
java代码:
/**
* 验证码保存到session
* @param response
*/
@RequestMapping(value = "checkCaptcha")
public void checkCaptcha(HttpServletResponse response){
response.setContentType("text/html");
PrintWriter writer = null;
try {
writer = response.getWriter();
String captcha  = (String) SecurityUtils.getSubject().getSession().getAttribute("captcha");
writer.println(captcha);
} catch (InvalidSessionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(writer!=null){
writer.close();
}
}
}
/**
* 生成验证码图片
* @param response
*/
@RequestMapping(value = "captcha")
public void captcha(HttpServletResponse response) {
OutputStream out = null;
try {
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
   response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
   response.addHeader("Cache-Control", "post-check=0, pre-check=0");
   response.setHeader("Pragma", "no-cache"); 
Object[] objs = ImageUtil.createImage();
SecurityUtils.getSubject().getSession().removeAttribute("captcha");
SecurityUtils.getSubject().getSession()
.setAttribute("captcha", objs[0].toString().toUpperCase());
BufferedImage image = (BufferedImage) objs[1];
response.setContentType("image/jpeg");
out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


package com.rdkl.qmjs.utils;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;


import javax.imageio.ImageIO;


public final class ImageUtil {
// 验证码字符集
/*private static final char[] chars = { 
'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'};*/
private static final char[] chars = { 
'2', '3', '4', '5', '6', '7', '8', '9', 
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
// 字符数量
private static final int SIZE = 4;
// 干扰线数量
private static final int LINES = 5;
// 宽度
private static final int WIDTH = 80;
// 高度
private static final int HEIGHT = 40;
// 字体大小
private static final int FONT_SIZE = 24;


/**
* 生成随机验证码及图片
* Object[0]:验证码字符串;
* Object[1]:验证码图片。
*/
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
// 1.创建空白图片
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.获取图片画笔
Graphics graphic = image.getGraphics();
// 3.设置画笔颜色
graphic.setColor(Color.gray);
// 4.绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 5.画随机字符
Random ran = new Random();
for (int i = 0; i <SIZE; i++) {
// 取随机字符索引
int n = ran.nextInt(chars.length);
// 设置随机颜色
graphic.setColor(getRandomColor());
// 设置字体大小
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 画字符
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);
// 记录字符
sb.append(chars[n]);
}
// 6.画干扰线
for (int i = 0; i < LINES; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
// 7.返回验证码和图片
return new Object[]{sb.toString(), image};
}


/**
* 随机取色
*/
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(128), 
ran.nextInt(128), ran.nextInt(128));
return color;
}

public static void main(String[] args) throws IOException {
Object[] objs = createImage();
BufferedImage image = (BufferedImage) objs[1];
OutputStream os = new FileOutputStream("d:/1.jpg");
ImageIO.write(image, "jpeg", os);
os.close();
}


}


0 0
原创粉丝点击