简易的验证码生成

//创建一张图片大小为68宽22高
BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
//得到这张图片
Graphics g = bi.getGraphics();
Color c = new Color(200,150,255);
//设置上下文颜色
g.setColor(c);
//使用上下文的颜色填充图片
g.fillRect(0, 0, 68, 22);
//使用字符数组去获得随机数
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random r = new Random();
int len=ch.length,index;
StringBuffer sb = new StringBuffer();
for(int i=0; i<4; i++){
index = r.nextInt(len);
//重新设置上下文颜色给图片填随机数
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
//填写随机数这里一次填一个字符,位置y坐标为18,x为当前一个字符位置+3
g.drawString(ch[index]+"", (i*15)+3, 18);
//string的流用来通知验证码是什么
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());

下面是html页面

<%@ 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">
<script type="text/javascript" src="/identifying_code/jq/jquery-1.7.2.min.js"></script>
<title>验证码生成</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$(".img").bind("click",function(){
var timestamp = new Date().getTime();
$(this).attr("src",$(this).attr("src") + '?' +timestamp );//注意不加时间戳可能刷新不到(特别是微信浏览器)
});
});


function judge(test,password,user){

if(test==""||user==""||password==""){
if(test=="")
alert("验证码不能为空");
else if(user=="")
   alert("用户名不能为空");
   else if(password=="")
   alert("密码不能为空");   
return false;
}else{
return true;
}
}
function go(){
var test=$("#yzm").val();
var user=$("input[name='user']").val();
var password=$("input[name='password']").val();
var bool=judge(test,user,password);

     if(bool==true){
   
    send(test);
 
}
}
function send(test) {
alert("ppx");
$.ajax({
url:"/identifying_code/Login",
type:"POST",
dataType:"text",
data:{
       "test":test,
       "user":user,
       "password":password
      },                                                    
success:function(data){

alert(data);
   
},
error:function(){
alert("请确认当前网络环境后,重新请求");
/* location.href ="http://www.baidu.com"; */
}



});
}
</script>
<center>
<div style="border: 1px solid red;">
<form action="" method="post" >
<table>
<tr><td>用户名:<input type="text" name="user" placeholder="请输入用户名:"/></td></tr>
<tr><td>密码:&nbsp;&nbsp;<input type="password" name="password" placeholder="默认密码为1至8" /></td></tr>
<tr><td>验证码:<input id="yzm" type="text" name="test"/></td><td><img class="img" alt="验证码"  src="<%=request.getContextPath()%>/Confirmation"></td></tr>
<tr><td><input type="button" value="提交" onclick="go();"/><td></tr>


</table>
</form>
</div>
</center>


</body>


</html>

效果:



猜你喜欢

转载自blog.csdn.net/qq_34299694/article/details/80970993