Servlet实现验证码功能
package com.servlet;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.imageio.ImageIO;public class Image extends HttpServlet {public void destroy() {}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 设置编码格式response.setContentType("image/jpeg");// 创建图片的大小int width = 85;int height = 20;// 创建一个img对象BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Random ran = new Random();// 得到画笔Graphics g = img.getGraphics();// 设置画笔的样式Color c = g.getColor();Font f = g.getFont();g.setColor(Color.pink);// 设置背景色g.fillRect(0, 0, width, height); // 填充背景色// 文字的操作StringBuffer sb = new StringBuffer();g.setFont(new Font("黑体", Font.BOLD, 16));for (int i = 0; i < 4; i++) {g.setColor(new Color(ran.nextInt(100), ran.nextInt(100), ran.nextInt(100)));String num = String.valueOf(ran.nextInt(10));g.drawString(num, i * 20 + 10, 15);sb.append(num);}// 恢复默认的画笔g.setColor(c);g.setFont(f);// 给服务器保存验证码字符串request.getSession().setAttribute("yan", sb);// 缓存清空response.setHeader("Pragma", "no-store"); // 本地机是否产生缓存文件response.setDateHeader("expires", 0); // 生效时间response.setHeader("Pragma", "no-cache"); // 清空// 输出图片ImageIO.write(img, "jpeg", response.getOutputStream());}}
?