使用Servlet实现网页验证码功能是我们jsp的实验之一,主要是为了掌握Servlet在JSP开发中的应用,其主要要求是:
(1)能够响应来自客户端的GET请求,不响应POST和其他请求;
(4)同时将验证码字符串放入session中,以便将来客户端提交验证码时检查是否一致。
其主要的实现代码:(Servlet)
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class CheckCode
*/
@WebServlet("/CheckCode")
public class CheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
private int width = 100;
private int height = 30;
private final char[] code = { 'A', 'B', 'C', 'D', 'E', 'F', 'G','H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6','7', '8', '9' };
//因为0与0相似,故没有0在此
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
BufferedImage Img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //生成图形
Graphics g = Img.getGraphics(); //实例化
//填充背景颜色
Random random = new Random();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
//设置字体
Font word = new Font("Arial", Font.PLAIN, 22);
g.setColor(Color.black);
g.setFont(word);
//干扰图线
g.setColor(Color.ORANGE);
for (int i = 0; i < 90; i++) {
int x= random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 生成随机数
StringBuffer randomCode = new StringBuffer();
int codeCount = 4; //设置字符个数
//定义颜色三素
int red = 0, green = 0, blue = 0;
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(code[random.nextInt(35)]); // 随机产生的颜色将验证码绘制到图像中
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i + 1) * 16, 22);
randomCode.append(strRand);
}
//将四位数字的验证码保存到Session中
HttpSession session = request.getSession();
session.setAttribute("truecode", randomCode.toString());
// 设置图像缓存为no-cache
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/gif");
//将最终生产的验证码图片输出到Servlet的输出流中
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(Img, "gif", sos);
sos.flush();
sos.close();
}
}