servlet 产生随机验证码
servlet实现代码:
import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.image.codec.jpeg.*; public class PrintServlet extends javax.servlet.http.HttpServlet{ //设置要随机生成的数字 public static final char[] CHARS = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; //随机器 public static Random random = new Random(); //随即获取4位数 public static String getRandomString() { StringBuffer sb = new StringBuffer(); for(int i=0; i<4; i++) { sb.append(CHARS[random.nextInt(CHARS.length)]); } return sb.toString(); } //获取随机产生的颜色 public static Color getRandomColor() { return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } //返回颜色的反色 public static Color getReverseColor(Color c) { return new Color(255-c.getRed(), 255-c.getGreen(), 255-c.getBlue()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/jpeg"); //设置输出的类型 String randomString = getRandomString(); req.getSession(true).setAttribute("randomString", randomString); //将获得的随机字符放回session int width = 120; int height = 30; Color color = getRandomColor(); Color reverse = getReverseColor(color); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //创建一个彩色图片 Graphics2D g = bi.createGraphics(); //获取绘图对象 g.setFont(new Font("宋体", Font.ITALIC, 16)); //设置随机字符的字体 Color c = g.getColor(); g.setColor(color); //设置绘制随机字符背景的颜色 g.fillRect(0, 0, width, height); //绘制随机字符的背景 g.setColor(reverse); g.drawString(randomString, 18, 20); //绘制字符 g.setColor(c); //设置随机字符中的干扰点 for(int i=0, n=random.nextInt(80); i<n; i++) { g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); //随机干扰点 } ServletOutputStream out = resp.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); //设置转码器 encoder.encode(bi); //对图片进行编码 out.flush(); } }
然后web.xml配置好就行.