public class CheckCodeServlet extends HttpServlet { public void servlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 畫畫 BufferedImage image = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random r = new Random(); g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255))); g.fillRect(0, 0, 60, 20); // 生成一個隨機數,而且畫到內存映射對象上 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String number = ""; for (int i = 0; i < 5; i++) { number += str.charAt(r.nextInt(str.length())); } HttpSession session = request.getSession(); session.setAttribute("number", number); System.out.println(number); g.setColor(new Color(0, 0, 0)); g.drawString(number, 10, 15); // 加一些干擾線 for (int i = 0; i < 5; i++) { g .setColor(new Color(r.nextInt(255), r.nextInt(255), r .nextInt(255))); g.drawLine(r.nextInt(60), r.nextInt(20), r.nextInt(60), r .nextInt(20)); } // 2 將圖片壓縮並輸出到客戶端 response.setContentType("image/jpeg"); OutputStream ops = response.getOutputStream(); javax.imageio.ImageIO.write(image, "jpeg", ops); } }