Java 图形验证码的生成和验证

发布于:2021-09-21 18:49:25

1. 导入第三方包,主要用来生成图形验证码



cn.hutool
hutool-all
4.6.8

2. 获取生成的图形验证码图片流,验证图片验证码


package com.JXWorkApi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.JXWork.result.Result;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;


/**
* 图形验证码生成
*
* 使用HuTool的captcha在内存中生成的验证码图片,并将绘制在图片上的验证码存放到session中用于后续验证
最后通过OutputStream将生成的图片进行输出
将页面提交的验证码和存放在session中的验证码对比来进行校验
*
* @author TF12778 2019/10/6 15:46
*/
@Controller
@RequestMapping(value = "/captcha")
public class HuToolController {

private static Log logger = LogFactory.getLog(HuToolController.class);
/**
* 获取图形验证码
* http://localhost:9999/JXWorkApi/captcha/getShearCaptcha
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "/getShearCaptcha", method = RequestMethod.GET)
public Result getShearCaptcha(HttpServletRequest request, HttpServletResponse response) {

OutputStream out = null;
try {
out = response.getOutputStream();// 取得输出流
//定义图形验证码的长、宽、验证码字符数、干扰线宽度
ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
//ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
//图形验证码写出,可以写出到文件,也可以写出到流
// captcha.write("/Users/sunww/Desktop/shear.png");
captcha.write(out);
//验证图形验证码的有效性,返回boolean值
boolean checkPass = captcha.verify(captcha.getCode());
logger.info(checkPass);
// 将生成的验证码code放入sessoin中
request.getSession().setAttribute("code", captcha.getCode());
out.flush(); // 将缓存中的数据立即强制刷新, 将缓冲区的数据输出到客户端浏览器
out.close(); // 关闭输出流

return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return new Result("error", "图片获取失败", "", null, "500" );
}

/**
* 验证图形码(这一步其实可以放到登录拦*髦腥プ觯
* http://localhost:9999/JXWorkApi/captcha/verifyCode?code=e2xr
* @param inCode 前端输入的图形验证码code
* @param req
* @return
*/
@ResponseBody
@RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
public Result verifyCode(String inCode, HttpServletRequest req) {

// 获取存放在session中的验证码
String code = (String) req.getSession().getAttribute("code");
// 获取页面提交的验证码
// String inputCode = req.getParameter("code");
String inputCode = inCode;
if(code.toLowerCase().equals(inputCode.toLowerCase())) { // 验证码不区分大小写
return new Result("success", "验证成功", "", null, "200" );
}
return new Result("error", "验证失败", "", null, "500" );
}
}

3. 测试结果:


获取的图片如下所示:



图形验证码验证:


?

相关推荐

最新更新

猜你喜欢