1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page import="java.util.Random"%> 4 <%@ page import="java.io.OutputStream"%> 5 <%@ page import="java.awt.Color"%> 6 <%@ page import="java.awt.Font"%> 7 <%@ page import="java.awt.Graphics"%> 8 <%@ page import="java.awt.image.BufferedImage"%> 9 <%@ page import="javax.imageio.ImageIO"%> 10 <% 11 int width = 60; 12 int height = 32; 13 //create the image 14 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 15 Graphics g = image.getGraphics(); 16 // set the background color 17 g.setColor(new Color(0xDCDCDC)); 18 g.fillRect(0, 0, width, height); 19 // draw the border 20 g.setColor(Color.black); 21 g.drawRect(0, 0, width - 1, height - 1); 22 // create a random instance to generate the codes 23 Random rdm = new Random(); 24 String hash1 = Integer.toHexString(rdm.nextInt()); 25 System.out.print(hash1); 26 // make some confusion 27 for (int i = 0; i < 50; i++) { 28 int x = rdm.nextInt(width); 29 int y = rdm.nextInt(height); 30 g.drawOval(x, y, 0, 0); 31 } 32 // generate a random code 33 String capstr = hash1.substring(0, 4); 34 //将生成的验证码存入session 35 session.setAttribute("validateCode", capstr); 36 g.setColor(new Color(0, 100, 0)); 37 g.setFont(new Font("Candara", Font.BOLD, 24)); 38 g.drawString(capstr, 8, 24); 39 g.dispose(); 40 //输出图片 41 response.setContentType("image/jpeg"); 42 out.clear(); 43 out = pageContext.pushBody(); 44 OutputStream strm = response.getOutputStream(); 45 ImageIO.write(image, "jpeg", strm); 46 strm.close(); 47 %>