public void doCreateCodeAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "-1");
CaptchaUtil util = CaptchaUtil.Instance();
// 将验证码输入到session中,用来验证
String code = util.getString();
request.getSession().setAttribute("code", code);
System.out.println(request.getSession().getAttribute("code"));
// 输出打web页面
ImageIO.write(util.getImage(), "jpg", response.getOutputStream());
}
↑在控制层的java类里面写,方便页面读取调用
<input id="code" name="std6" class="input2" type="text" />
<div class="change_put"><img id="img" src="<spring:url value='/api/doCreateCode' />" οnclick="refresh()" /></div>
<button class="change" οnclick="refresh()" value="" >换一张</button>
↑HTML页面使用
function refresh() {
var url = "你的路径名?number="+Math.random();
$("#img").attr("src",url);
}
js调用↑
private void doCheckCodeAction(HttpSession session, String code) throws UfdmException {
String codeSession = (String) session.getAttribute("code");
if (StringUtils.isEmpty(codeSession)) { //验证在session中获取到的验证码是否为空
//返回错误信息
}
if (StringUtils.isEmpty(code)) { //验证在session中获取到的验证码是否为空
//返回错误信息
}
if (!codeSession.equalsIgnoreCase(code)) {
// 验证码通过
}
}
JAVA类控制层中验证生成的图形验证码↑
工具类地址: