验证码作用:防止程序员用暴力的方式反复登录从而破解密码的一种方式。验证码每次刷新都会随机生成。
主要是利用Graphics这个类画验证码再以字节流的形式传给web。
package com.xuzengqiang.tour.user.web.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xuzengqiang.tour.common.exception.TourException;
import com.xuzengqiang.tour.common.web.servlet.BaseServlet;
//验证码的生成code
@SuppressWarnings("all")
public class VerificationCodeServlet extends BaseServlet
{
public void createCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// 设置清除缓存
response.setHeader("Cache-control", "no-cache");
response.setHeader("Prama", "no-cache");
response.setDateHeader("Expires", 0);
// 生成5位随机数
Random random = new Random();
StringBuffer code = new StringBuffer();
for (int i = 0; i < 5; i++)
{
int number = random.nextInt(26); // 生成0~25的随机数
if (number % 2 == 0)
{
code.append((char) number % 10);
}
else
{
code.append((char) (number + 'A'));
}
}
// 创建图片对象
int width = 100;
int height = 25;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(new Color(175, 175, 175));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
g.setColor(Color.WHITE);
g.fillRect(1, 1, width - 2, height - 2);
// 随机生成干扰线
for (int i = 0; i < 5; i++)
{
int startX = random.nextInt(width);
int startY = random.nextInt(height);
int endX = random.nextInt(width);
int endY = random.nextInt(height);
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawLine(startX, startY, endX, endY);
}
// 画验证码
g.drawString(code.toString(), 10, 23);
// 生成
g.dispose();
request.getSession().setAttribute("verificationCode", code);
// 图片发送
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(image, "JPEG", sos);
try
{
if (sos != null)
{
sos.close();
}
}
catch (Exception e)
{
throw new TourException("验证码生成错误!");
}
}
}
使用的时候直接图片的src="对应的servlet即可"。
刷新:不涉及页面的刷新,只是验证码的刷新。
jQuery(document).ready(function()
{
$(".volidate-Code a").click(function()
{
var url="/tour/doVerificationCodeServlet?action=createCode";
//加上时间戳,刷新验证码
url=url+"&date="+new Date();
$(".volidate-Code img").attr("src",url);
});
});