//用SERVLET画出一个验证图片 public class imageValidate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); response.setHeader("Cache-Control","public"); response.setHeader("Cache-Control","max-age=600"); int width=60, height=20; BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //获取图形上下文 Graphics g = bufferedImage.getGraphics(); //生成随机类 Random random = new Random(); // 画背景 g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); //画边框 g.setColor(Color.BLACK); g.drawRect(0,0,width-1,height-1); //设定字体 g.setFont(new Font("Times New Roman",Font.PLAIN,18)); // 取随机产生的认证码(4位数字) StringBuffer sRand = new StringBuffer(); for (int i=0;i<4;i++){ String rand=String.valueOf(random.nextInt(10)); sRand.append(rand); //将认证码显示到图象中 g.setColor(new Color(random.nextInt(225),random.nextInt(225),random.nextInt(225))); g.drawString(rand,13*i+6,16); } g.dispose(); request.getSession(true).setAttribute("checknum", sRand.toString()); ServletOutputStream responseOutputStream =response.getOutputStream(); // 输出图象到页面 ImageIO.write(bufferedImage, "JPEG", responseOutputStream); //以下关闭输入流! responseOutputStream.flush(); responseOutputStream.close(); }
//在JSP页面中可以直接引用上述servlet产生的随机码 <td>验证码:</td> <td><input type="text" name="checkNum" style="width:200px"><img src="/shoppingcart/servlet/imageValidate"></td>