1.首先是ValiImageServlet.java文件,此文件用来生成一张验证码的图片,同时使用HttpSession来保存并传递验证码的内容
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// 在doGet中调用doPost
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// 首先设置浏览器不缓存
response.setHeader("cache-control", "no-cache");
response.setHeader("Expire", "-1"); // >0为缓存
response.setHeader("pragma", "no-cache");
// 存储正确的验证码
String vali_code = "";
String Vali_str = "abcdefghijklmnopqrstuvwsyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Color[] colors =
{ Color.BLACK, Color.RED, Color.BLUE };
// 1.创建图像
int width = 120, height = 40;
int x_offset = 5, y_offset = 20;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
// 2.创建画布
Graphics2D g = img.createGraphics();
// 3.为画布添加背景颜色为亮灰色
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, width, height);//fillRect是包括矩形框内部
// 4.为画布添加边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width - 1, height - 1);//drawRect是绘制矩形边框
// 5.绘制干扰线
for (int i = 0; i < 10; i++)
{
g.setColor(new Color(randNum(0, 255), randNum(0, 255), randNum(0, 255)));
g.drawLine(randNum(0, width), randNum(0, height), randNum(0, width), randNum(0, height));
}
g.setFont(new Font("黑体", Font.BOLD, 20));
for (int i = 0; i < 4; i++)
{
int r = randNum(-180, 180);
String code = Vali_str.charAt(randNum(0, Vali_str.length() - 1)) + "";
g.rotate(r / 180 * Math.PI);
g.setColor(colors[randNum(0, colors.length)]);
g.drawString(code, x_offset + i * 30, y_offset);
g.rotate(-r / 180 * Math.PI);
vali_code += code;
}
//将验证码的内容存储在HttpSession中
HttpSession session = request.getSession();
session.setAttribute("Valicode", vali_code);
// 通过response的输出流打给浏览器
ImageIO.write(img, "jpg", response.getOutputStream());
}
//单列模式
private Random random = new Random();
//随机生成begin和end之间的一个int值
private int randNum(int begin, int end)
{
return random.nextInt(end - begin) + begin;
}
2.在HTML页面中显示验证码的图片
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>vali.html</title>
<script type="text/javascript">
function changeValiImage(img)
{
img.src = "/TestPro/servlet/ValiImageServlet?time=" + new Date().getTime();
}
</script>
</head>
<body>
<form action="/TestPro/servlet/CheckValiServlet">
<br/>
验 证 码:<img src="/TestPro/servlet/ValiImageServlet" onclick="changeValiImage(this)" /><br/>
输入验证码:<input type="text" name="ValiImage" id = "vali"/><br/>
<input type="submit" />
</form>
</body>
</html>
【说明】上面使用了Javascript语言,产生点击验证码图片更换验证码,每次点击验证码图片更改img的src属性值,需要注意的是通过Date来改变每次访问的url不同。
3.下面是CheckValiServlet.java,用来检测验证码的正确性
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String vali_sys = request.getSession().getAttribute("Valicode").toString();
//需要注意的是Parameter-key是input的name
String vali_user = request.getParameter("ValiImage");
if (vali_user.equals(vali_sys))
{
//验证成功,登录到loginsuccess.html页面,可以使用下面三种方式
//1.验证码正确,请求重定向
response.setStatus(302);
response.setHeader("Location", "/TestPro/loginsuccess.html");
//2.请求重定向的第二种方式
response.sendRedirect("/TestPro/loginsuccess.html");
//3.使用Refresh跳转
response.setHeader("Refresh","3;url=/TestPro/loginsuccess.html");
}else
{
//验证码错误,提示验证失败
response.getOutputStream().write("验证码错误".getBytes("utf-8"));//指定文本信息的编码格式
response.setContentType("text/html;charset=utf-8");//通过HTTP响应头指定浏览器解码格式
//response.setHeader("Content-Type", "text/html;charset=utf-8");
}
}