为网上书店编程示例的登录页面 index . jsp 添加验证码功能。实现思路 Random 类可产生指定范围的随机数,将产生的随机数保存在 session 对象中,在 index . j sp页面添加一个文本框输入验证码,在 checkUser . jsp 页面将提交过来的验证码文本框中的值与保存在 request 对象中的值进行比较



为网上书店编程示例的登录页面 index . jsp 添加验证码功能。实现思路 Random 类可产生指定范围的随机数,将产生的随机数保存在 session 对象中,在 index . j sp页面添加一个文本框输入验证码,在 checkUser . jsp 页面将提交过来的验证码文本框中的值与保存在 request 对象中的值进行比较



关注这个不难,网上代码也很多,把思路理清楚就行。
首先,需要在 index.jsp 页面中生成并显示验证码图片,并将验证码值保存在 session 中:
<%
// 生成验证码
Random random = new Random();
String code = "";
for (int i = 0; i < 4; i++) {
code += String.valueOf(random.nextInt(10));
}
// 将验证码存入 session 中
session.setAttribute("code", code);
%>
<!-- 显示验证码图片 -->
<img src="code.jsp" /><br />
<!-- 输入验证码 -->
<input type="text" name="code" />
其中 code.jsp 是用于生成验证码图片的页面,代码如下:
<%
// 从 session 中取出验证码
String code = (String)session.getAttribute("code");
// 创建 BufferedImage 对象
BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 设置背景色和前景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, 80, 30);
g.setColor(Color.BLACK);
// 绘制验证码文字
g.drawString(code, 20, 20);
// 添加干扰线
for (int i = 0; i < 8; i++) {
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawLine(random.nextInt(80), random.nextInt(30), random.nextInt(80), random.nextInt(30));
}
// 将图像写入输出流中
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
最后,在 checkUser.jsp 页面中获取提交过来的验证码值,并与 session 中的值进行比较:
// 获取提交过来的验证码值
String code = request.getParameter("code");
// 获取 session 中保存的验证码值
String sessionCode = (String)session.getAttribute("code");
// 比较验证码值
if (code.equals(sessionCode)) {
// 验证码正确,执行登录操作
// ...
} else {
// 验证码错误,返回到登录页面
response.sendRedirect("index.jsp");
}