Step 1.随机验证码
一步一步来,要生成验证码图片,首先要有验证码,然后才能在画在图片上。为了能够灵活控制验证码,特别编写了SecurityCode类,它向外提供随机字符串。并且可以控制字符串的长度和难度。SecurityCode类中提供的验证码分三个难度,易(全数字)、中(数字+小写英文)、难(数字+大小写英文)。难度使用枚举SecurityCodeLevle表示,避免使用1、2、3这样没有明确意义的数字来区分。
同时,还控制了能否出现重复的字符。为了能够方便使用,方法设计为static。
SecurityCode类:
importjava.util.Arrays;
publicclass SecurityCode {
}
Step 2.图片
importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.util.Random;
importcom.sun.image.codec.jpeg.ImageFormatException;
importcom.sun.image.codec.jpeg.JPEGCodec;
importcom.sun.image.codec.jpeg.JPEGImageEncoder;
publicclass SecurityImage {
}
Step 3.验证码与Struts 2结合
这里采用的是action注解的方式来配置。
private String verifycode;
private ByteArrayInputStream imageStream;
/**
*
* @Title: register
* @Description: 注册时输入验证码
* @param @return
* @return String
* @throws
*/
@Action(value = "/ValidCode", interceptorRefs = @InterceptorRef("defaultStack"), results = {
@Result(name = "success", type = "stream",
params = {"contentType", "image/jpeg","inputName", "imageStream", "bufferSize", "4096" })
})
public String validCode(){
//如果开启Hard模式,可以不区分大小写
//String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();
//获取默认难度和长度的验证码
String securityCode = SecurityCode.getSecurityCode();
System.out.println("securityCode=="+securityCode);
imageStream = SecurityImage.getImageAsInputStream(securityCode);
//放入session中
ActionContext.getContext().getSession().put("securityCode", securityCode);
return SUCCESS;
}
/**
* 判断用户输入验证码是否正确
*
* @return
*/
@Action(value = "/user/verifycode", interceptorRefs = @InterceptorRef("defaultStack"), results = { @Result(name =
SUCCESS, type = "json") })
public String verify() {
System.out.println("verifycode==" + verifycode);
String securityCode=(String)ActionContext.getContext().getSession().get("securityCode");
System.out.println("securityCode==" + securityCode);
if (!securityCode.equals(verifycode)) {
errorname = "codewrong";
}
return SUCCESS;
}
public ByteArrayInputStream getImageStream() {
return imageStream;
}
public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}
@JSON(serialize = false)
public String getVerifycode() {
return verifycode;
}
public void setVerifycode(String verifycode) {
this.verifycode = verifycode;
}
如果你采用的是struts.xml配置文件,
<action name="ValidCode" class="ValidCode">
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
</result>
</action>
3)前台JSP
定义一个img元素,将src指向ValidCode.action就可以了,浏览器向Action发送请求,服务器将图片流返回,图片就能够显示了。
<!-- 验证码 --> <input type="text" id="verifycode" name="verifycode" οnblur="verify()"/> <img src="ValidCode.action" id="Verify" style="cursor:pointer;" alt="看不清,换一张"/> <!-- 验证码 end-->
4)JS
//点击图片更换验证码 $(function () { //点击图片更换验证码 $("#Verify").click(function(){ $(this).attr("src","ValidCode.action?timestamp="+new Date().getTime()); }); }); /*验证用户用户输入验证码是否正确 */ function verify() { var verifycode = $("#verifycode").val(); $("#sp").html(""); $.ajax({ type : "POST", url : 'user/verifycode.action', data : { "verifycode" : verifycode }, dataType : "json", success : function(msg) { var error = msg.errorname; if (error == 'codewrong'){ $("#sp").html("验证码错误"); } }, }); }