java验证码实现

@RequestMapping(value={"image"})
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//controller中生成验证码的方法
/*
* bufferedImage(参数一,参数二,参数三)
* 参数一:表示验证码的长度 68
* 参数二:表示验证码的宽度 25
*/
BufferedImage bufferedImage = new BufferedImage(68, 25, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
/*
* Color(参数一,参数二,参数三)
* 三个参数表示的是三基色。可以自己调整
*/
Color color = new Color(225, 230, 246);
graphics.setColor(color);
//设置字体样式和大小
graphics.setFont(new Font("Times New Roman", Font.PLAIN, 20));
graphics.fillRect(0, 0, 68, 25);
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random random = new Random();
int length = chars.length;
StringBuffer buffer = new StringBuffer();
int index;
for (int i = 0; i < 4; i++) {
index = random.nextInt(length);
graphics.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
graphics.drawString(chars[index] + "", (i * 15) + 3, 18);
buffer.append(chars[index]);
}
request.getSession().setAttribute("code", buffer.toString());
ImageIO.write(bufferedImage, "JPG", response.getOutputStream());

}

/**
* controller中验证码验证方法 
*/
@RequestMapping(value={"checkCode"})
private String checkCode(CwUser user,HttpSession session, String code,RedirectAttributes redirectAttributes) {
String codeSession = (String) session.getAttribute("code");
System.out.println(user+"------"+codeSession);
if (code.equalsIgnoreCase(codeSession)) {
if (cwUserService.login(user) != null) {
addMessage(redirectAttributes, "登录成功");
System.out.println("登录成功");
return "redirect:" + adminPath + "/aa/bb/loginList";
}else {
addMessage(redirectAttributes, "用户名或密码错误");
System.out.println("用户名或密码错误");
return "redirect:" + adminPath + "/aa/bb/";
}
}else {
addMessage(redirectAttributes, "验证码有误");
System.out.println("验证码有误");
return "redirect:" + adminPath + "/aa/bb/";
}
}

/** 
* jsp页面代码 
*/ 

<form id="inputForm" action="${ctx}/aa/bb/checkCode" method="post" class="form-horizontal">

账户:<input id=name type=text name=name required >
密码:<input id=name type=text name=password required >
验证码:<input type="text" name="code" id="code" >//放置一个img标签,src图片地址里写controller里生成验证码的方法路劲。onclick方法是点击验证码更换,也可以点击看不清来更换

<img id="image" alt="输入验证码" src="${ctx}/aa/bb/image" onclick="javascript: reload();" />
<a href="javascript: reload();">看不清</a><br>
<input id="btnSubmit" class="btn btn-primary" type="submit" value="登 录"/>
</form>

/** 
* 更换验证码方法
*/ 

<script type="text/javascript">
  function reload() {
    var time = new Date().getTime();
    document.getElementById("image").src = "${ctx}/aa/bb/image?id=" + time;
  }

</script>

原文地址:https://www.cnblogs.com/12kk/p/6767497.html