Servlet生成驗證碼例項
阿新 • • 發佈:2018-11-08
新建一個Servlet
在doGet或者doPost方法中提供下面的程式碼。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 110; int height = 25; //在記憶體中建立影象物件 BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //建立一個畫筆 Graphics g = img.getGraphics(); //給圖片添背景顏色 g.setColor(Color.PINK); //填充面積減去邊框的大小 g.fillRect(1,1, width-2, height-2); //給邊框新增顏色 g.setColor(Color.RED); g.drawRect(0,0, width-1, height-1); //設定文字樣式 g.setColor(Color.BLUE); g.setFont(new Font("宋體",Font.BOLD|Font.ITALIC,15)); //給圖片新增文字內容,驗證碼上面的文字 /* * 第一個引數:內容 * 第二個引數:上距離 * 第三個引數:左距離 */ //顯示的內容生成4位的隨機數 Random rand = new Random(); int position = 20; for(int i = 0;i < 4;i++){ int count = rand.nextInt(10); g.drawString(count+"", position,20); position = position+20; } //將圖片物件以流的方式輸出到客戶端 ImageIO.write(img, "jpg",response.getOutputStream()); // }
效果演示: