图片验证码获取及验证
流程图
服务层
接口 代码片
.
public BufferedImage getImage(HttpSession httpSession);
实现类 代码片
.
@Override
public BufferedImage getImage(HttpSession httpSession) {
BufferedImage bufferedImage = new BufferedImage(W, H, BufferedImage.TYPE_INT_BGR);
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.white);
graphics.fillRect(0, 0, W, H);
StringBuffer StringBuffer = new StringBuffer();
Font font = new Font("微软雅黑", Font.BOLD, 24);
//随机验证码字符
for(int i=0;i<4;i++) {
String zm=getZM();
StringBuffer.append(zm);
graphics.setFont(font);
graphics.setColor(randomColor());
graphics.drawString(zm,(1+i)*(W/6),H*3/4);
}
String code = StringBuffer.toString();
httpSession.setAttribute("code", code);//将code验证码存入session
huaXian(graphics);
return bufferedImage;
}
//添加干扰线
public void huaXian(Graphics graphics) {
Random random = new Random();
for(int i=0;i<5;i++) {
graphics.setColor(randomColor());
int x1 = random.nextInt(20);
int y1 = random.nextInt(H);
int x2=(W-20)+random.nextInt(20);
int y2=random.nextInt(H);
graphics.drawLine(x1, y1, x2, y2);
}
}
public Color randomColor() {
Random random = new Random();
int R = random.nextInt(256);
int G = random.nextInt(256);
int B = random.nextInt(256);
Color color = new Color(R,G,B);
return color;
}
public String getZM() {
Random random = new Random();
//获取26个小写字母
String str = String.valueOf((char)(97+random.nextInt(26)));
//数字
int str1 = random.nextInt(10);
if(random.nextInt(2)==1) {
if(random.nextInt(2)==1) {
return str;
}else {
return str.toUpperCase();
}
}else {
return str1 + "";
}
}
控制层
代码片
.
@RequestMapping("getcode")
public void getcode(HttpServletResponse httpServletResponse,HttpSession httpSession) {
BufferedImage image=hwservice.getImage(httpSession);
try {
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
ImageIO.write(image, "png", outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping("checkCode/{code}")
@ResponseBody
public String checkCode(@PathVariable("code")String code,HttpSession httpSession) {
//取出session中的code验证码
String checkCode = httpSession.getAttribute("code").toString();
if(checkCode!=null) {
if(checkCode.equals(code)) {
return"OK";
}
}
return"NO";
}
客户端
代码片
.
//根据自身环境需求设置大小样式
<div class="form_text_ipt" style="position: relative;">
<input name="name" type="text" placeholder="验证码" id="codeid" />
<img src="authCode" id="codeImg" onclick="chageCode()" style="width: 90px; height: 30px; position: absolute; top: 3px; right: 5px;" />
</div>
//点击图片验证码进行切换
function changeCode() {
$("#codeImg").attr('src', 'authCode?abc=' + Math.random());
}
//获取验证码输入框的值
var code-id = $("#codeid").val();
//发送请求将输入的验证码与后端生成的进行比较
$.get("checkCode/"+captcha,function(result){
console.log(result);
});
有需要了解的可以留言,看到必回!