在开发web项目,登录注册模块可能会需要验证码功能,本文的教程是如何设置一个字母和数字的验证码.
我们在实现验证码,首先需要生成一个验证码,并将其转换为图片,添加到网页中,然后获取用户输入的验证码与服务器生成的验证码做比较.当点击验证码时,会重新生成一个验证码.验证码使用到的技术有session,js事件.
eclipse中实现验证码的步骤:
- 准备一个生成验证码图片的工具类
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.创建一对象,在内存中图片(验证码图片对象)
BufferedImage img = new BufferedImage(80, 28, BufferedImage.TYPE_INT_RGB);
// 2.美化图片
// 2.1 填充背景色
Graphics g = img.getGraphics();// 画笔对象
g.setColor(Color.pink);// 设置画笔颜色
g.fillRect(0, 0, img.getWidth(), img.getHeight());// 填充背景色
// 2.2画边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
// 生成随机角标
Random ran = new Random(); // 随机数生产器
// 创建StringBuilder对象:缓冲区中
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {// 1-4四个字符
int index = ran.nextInt(str.length());
// 获取字符
char ch = str.charAt(index);// 随机字符
g.setFont(new Font(ch + "", 20, 20));// 设置字体大小
// 将产生的四个字符ch拼接到缓冲区中
sb.append(ch);
// 2.3写验证码
// 将四个随机字符写到图片上,後面两个参数代表字符的位置
g.drawString(ch + "", img.getWidth() / 5 * i, img.getHeight() * 5 / 6);
}
// 需要将图片的验证码存储会话域中,session域中
request.getSession().setAttribute("checkCode_image", sb.toString());// 将缓冲区对象转换成字符串
// 2.41画干扰线
g.setColor(Color.green);
// 随机生成坐标点
for (int i = 0; i < 5; i++) {
int x1 = ran.nextInt(img.getWidth());
int x2 = ran.nextInt(img.getWidth());
int y1 = ran.nextInt(img.getHeight());
int y2 = ran.nextInt(img.getHeight());
g.drawLine(x1, y1, x2, y2);
}
// 2.42画干扰线,换个颜色划
g.setColor(Color.CYAN);
// 随机生成坐标点
for (int i = 0; i < 5; i++) {
int x1 = ran.nextInt(img.getWidth());
int x2 = ran.nextInt(img.getWidth());
int y1 = ran.nextInt(img.getHeight());
int y2 = ran.nextInt(img.getHeight());
g.drawLine(x1, y1, x2, y2);
}
// 3.将图片输出到页面展示
ImageIO.write(img, "jpg", response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
}
- 创建一个jsp页面
jsp页面中添加一个表单
from表单中有
一个input文本框用来让用户输入验证码,
一个图片来放置验证码图片
一个span标签用来提示信息
一个提交按钮用来提交表单
- 使用jQuery技术为验证码添加点击事件.
jQuery技术需要一个js文件放入当前项目,并在使用jQuery的页面添加链接.
<script src="/js/jquery-1.11.3.min.js" type="text/javascript"></script>
- 使用jsp标签来获取域中的数据,并展示.
jsp标签的使用同样需要导入一个包到当前页面.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
最后的jsp页面代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码</title>
</head>
<script src="/js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#codeimg").click(function() {
//验证码点击事件,当点击验证码时重新生成一个验证码图片
this.src = "/CheckCodeServlet?time=" + new Date().getTime();
});
});
</script>
<style>
span{
color:red;
}
</style>
<body>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
<input type="text" name="code" id="code">
<img src="/CheckCodeServlet" id="codeimg" alt="验证码" height="28px" width="100px">
<span >
<c:if test="${not empty code}">
${code}
</c:if>
</span><br>
<input type="submit" value="提交">
</form>
</body>
</html>