您的位置:首页 > 其它

web创建form表单验证码

2016-01-09 16:37 375 查看
首先是工具类,用来绘制验证码

public class Verify {
//字符串,用来存储验证码中的字符
private String string;

public void setString(String string) {
this.string = string;
}
public String getString() {
return string;
}
//绘制验证码方法
public void getVerify(int width , int height , OutputStream out){
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();

// 绘制面板
graphics.setColor(Color.white);
graphics.fill3DRect(0, 0, width, height, true);

// 边框大小,颜色
graphics.setColor(Color.black);
graphics.draw3DRect(0, 0, width-1, height-1, true);

//随机存储四个字符
String string = "qwertyuiopasdfghjklzxcvbnm1234567890";
StringBuffer sb = new StringBuffer();
Random random = new Random();
String blank = "     ";
for (int i = 0; i < 4; i++) {
int next = random.nextInt(string.length());
sb.append(string.charAt(next)+blank);
}

//绘制干扰线
for(int i =0 ;i<4;i++){
//创建线的坐标
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
//创建颜色RGB三个范围值
int a = random.nextInt(255);
int b = random.nextInt(255);
int c = random.nextInt(255);
graphics.setColor(new Color(a,b,c));
graphics.drawOval(x1, y1, x2, y2);
}

//绘制四个验证码
graphics.setColor(Color.red);
String str = sb.toString();
graphics.drawString(str, width/8, height/2);

//拆分字符
StringBuffer buffer = new StringBuffer();
String[] split = str.split(blank);
for(String s : split){
buffer.append(s);
}

//存储字符串
setString(buffer.toString());

try {
ImageIO.write(image, "jpeg", out);
} catch (IOException e) {
throw new RuntimeException(e);
}

}

}


后台处理

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置response的数据格式
response.setContentType("image/jpeg");
//画验证码
Verify verify = new Verify();
verify.getVerify(100, 50, response.getOutputStream());
}


jsp部分,给”看不清”设置超链接,同时加上点击事件,时间处理时变换img的src属性,为了避免读取缓存,给超链接附加上了时间+随机数

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript">
function refresh(){
//使用时间作为参数避免浏览器从缓存
document.getElementById("img1").src="/day1116/Demo?now="+new Date()+""+Math.random();
}
</script>
</head>

<body>
<img src="${pageContext.request.contextPath}/Demo" id="img1"/><a href="#" onclick="refresh()">看不清,换一张</a>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: