生成后返回验证码字符
以上源码及其资料图片下载链接:http://pan.baidu.com/s/1bURheu 密码:5evt
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 生成验证码工具类
* @author nikolas511
*
*/
public class VerificationUtils{
private static int WIDTH=100;//图片宽
private static int HEIGHT=40;//图片长
public static String getVerification(HttpServletRequest request, HttpServletResponse response) throws IOException{
//构造一幅图片,并得到图行
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//设置图片的背景,并设置图片的边框
setBackGround(g);
//增加线条干扰
setLine(g);
//画出图片中的文字
String text = setText((Graphics2D)g);
//控制浏览器不要缓存,实际测试中浏览器不缓存
response.addDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma","no-cache");
//将图片用输出流输出到浏览器中
ImageIO.write(image, "jpg", response.getOutputStream());
return text;
}
private static String setText(Graphics2D g) {
int x=6,y=32;
String s ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Color[] color ={Color.BLACK,Color.RED,Color.DARK_GRAY,Color.MAGENTA,Color.ORANGE,
Color.YELLOW,Color.CYAN,Color.BLUE,Color.ORANGE,Color.GREEN,Color.PINK,
Color.GRAY};
String text = "";
for(int i=0;i<4;i++){
int num = new Random().nextInt(color.length);
String ch =s.charAt(new Random().nextInt(s.length()))+"";
text =text+ch;
double degree = (new Random().nextInt(30))*Math.PI/180;
if(!new Random().nextBoolean())degree=-degree;
Color c = color[num];
g.setColor(c);
g.setFont(new Font(ch,Font.BOLD,30));
g.rotate(degree,x,y);
g.drawString(ch,x,y);
g.rotate(-degree,x,y);
x+=25;//此处设置字符间距
}
return text;
}
private static void setLine(Graphics g) {
Color[] color ={Color.YELLOW,Color.CYAN,Color.BLUE,Color.ORANGE,Color.GREEN,Color.PINK};
for(int i=0; i<=10; i++){
int num = new Random().nextInt(color.length);
Color c = color[num];
g.setColor(c);
int x1 = new Random().nextInt(150);
int y1 = new Random().nextInt(40);
int x2 = new Random().nextInt(150);
int y2 = new Random().nextInt(40);
g.drawLine(x1, y1, x2, y2);
}
}
private static void setBackGround(Graphics g) {
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
}
}
此处测试以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;
import cn.pjj.utils.VerificationUtils;
@WebServlet("/VerificationServlet")
public class VerificationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = VerificationUtils.getVerification(request, response);
request.getSession().setAttribute("text", text);
System.out.println(text);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
String checknum = request.getParameter("checknum");
String text = (String) request.getSession().getAttribute("text");
if(text.equalsIgnoreCase(checknum)){
pw.write("images/MsgSent.gif");
}else{
pw.write("images/MsgError.gif");
}
pw.flush();
pw.close();
}
}
下面为jsp页面,当输入4个字符后发送ajax请求,此处需要导入jquery的js文件
图片例子
<%@ 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>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<table>
<tr>
<td>输入验证码:<input id="checknum" size="3" type="text" height="40" maxlength="4"
name="checknum" onkeyup="check()" /></td>
<td><span id="res"></span> </td>
<td><img id="image" onclick="changeImage(this)"
src="${pageContext.request.contextPath}/VerificationServlet"></td>
</tr>
</table>
<script type="text/javascript">
function changeImage(img) {
img.src = img.src + "?" + new Date().getTime();
$("#res").html("");
$("#checknum").val("");
}
//去掉两边的空格
function trim(str){
str = str.replace(/^\s*/,"");
str = str.replace(/\s*$/,"");
return str;
}
</script>
<script type="text/javascript">
function check(){
var $checknum = $("#checknum");
var $str = trim($checknum.val());
if($str.length==4){
$.ajax({
type:"POST",
url:"VerificationServlet?time=" + new Date().getTime(),
data:{"checknum":$str},
success:function(backData){
var $res = $("#res").html("");
$("<img src='"+backData+"' style='width:14px;height:14px' />").appendTo($res);
}
});
}else{
$("#res").html("");
}
}
</script>
</body>
</html>
以上源码及其资料图片下载链接:http://pan.baidu.com/s/1bURheu 密码:5evt