1.图片生成工具类
// 将字符数组转化成字符数组
char[] chars = this.getRandString().toCharArray();
for (int i=0; i<chars.length; i++) {
graphics.setColor(this.createRandColor());
String letter = new Character(chars[i]).toString();
// 这里调整字符的间距和高度,水平偏差为10,高度偏差为15
graphics.drawString(letter, (random.nextInt(10) + (this.fontSize-5)*(i+1) -5), (random.nextInt(10) + 25));
}
// 图片生效
graphics.dispose();
return image;
}
}
2.验证图片输出Servlet
// 生成的图片
BufferedImage image = imageGenerator.createImage();
// 随机字符串
String randString = imageGenerator.getRandString();
HttpSession session = request.getSession(true);
session.setAttribute("randString", randString);
// Servlet输出流
OutputStream out = response.getOutputStream();
// 将图片写入到输出流中去
ImageIO.write(image, "JPG", out);
// 强制刷新
out.flush();
// 关闭输出流
out.close();
}
}
3.校验码验证Servlet
String ucode = request.getParameter("ucode");
if (randString.equalsIgnoreCase(ucode)) {
out.println(true);
}
else {
out.println(false);
}
// 关闭输出流
out.close();
}
}
4. 测试验证的JSP页面
function login() {
if (isImageCodeRight) {
return true;
}
else {
return false;
}
}
function verify() {
var ucode = $("#ucode").val();
window.alert(ucode);
$.get("/imageVerify", {ucode:ucode}, function (data) {
window.alert(data);
if (data) {
$("#ucodemsg").html("验证通过");
isImageCodeRight = true;
}
else {
$("#ucodemsg").html("验证失败");
isImageCodeRight = false;
}
});
}
$(document).ready(function(){
$("#ucode").bind("change",verify);
$("#loginForm").bind("submit",login);
});
// --></mce:script>
</head>
<body>
<fieldset>
<legend>
用户登录
</legend>
<s:form name="loginForm" id="loginForm" action="/user/login.do" method="post" theme="simple">
<table>
<tr>
<td>
用户名
</td>
<td>
<s:textfield name="uname" id="uname" maxLength="20" />
</td>
<td id="unamemsg"></td>
</tr>
<tr>
<td>
密码
</td>
<td>
<s:password name="upass" id="upass" maxLength="20"/>
</td>
<td id="upassmsg"></td>
</tr>
<tr>
<td>
校验码
</td>
<td>
<s:textfield name="ucode" id="ucode" maxLength="5"/>
</td>
<td id="ucodemsg"></td>
</tr>
<tr>
<td colspan="2" align="right">
<a href="<%=imgUrl%>"><img src="/imageValidator" mce_src="imageValidator" alt="验证码图片" />
</a>
</td>
</tr>
<tr>
<td>
<s:submit value="提交" id="submit" />
</td>
<td align="center">
<s:reset value="重置" id="reset" />
</td>
</tr>
</table>
</s:form>
</fieldset>
</body>
</html>
5. 登录用的Action
6.struts.xml配置
7.效果演示
(1)验证成功
(2)验证失败
(3)登录成功
(登录失败)