验证码
获取4个随机数
String s = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
Random random = new Random();
String captcha = "";
for(int i=0;i<4;i++)
{
int a = random.nextInt(s.length());
char c = s.charSet(a);
captcha = captcha + c;
}
将随机数画到画布上
BufferedImage image = new BufferedImage(100,40,Buffered.TYPE_INT_BGR);
Graphics g = image.getGraphics();
Font font = new Font("",Font.BOLD,25);
g.setFont(font);
g.drawString(captcha,10,35);
将生成的随机数图片发送到客户端浏览器
OutputStream os = response.getOutputStream();
ImageIO.write(image,"jpg",os);
验证码不区分大小写
String captchaStr = captcha.toLowerCase();.
// or
String code = request.getParameter("code");
String rightCode = (String)request.getSession().getAttribute("code");
PrintWriter out = response.getWriter();
if(code!=null && code.equalsIgnoreCase(rightCode))//字符串不区分大小写
{
out.print(1);
}
else
{
out.print(0);
}
out.close();
切换验证码
$(document).ready(function(){
$("#changeCaptcha").click(function(){
var random = Math.random();
$("#captchaImg").attr("src","${pageContext.request.contextPath}/CaptchaServlet?method=getCaptcha&random="+random);
})
})