無外掛及工具純java生成驗證碼
1:html頁面
<body> <image id="code" src="DemoServlet"></image> <input type="button" value="看不清,換一張" id="btn" onclick="changeCode(this)" > <script type="text/javascript"> function changeCode(obj){ document.getElementById("btn").isDisabled=true; document.getElementById("code").src='DemoServlet?ts='+new Date().getTime(); } </script> </body>
2:後臺java程式碼(servlet doGet方法中
//生成圖片中的字元 String str = "abcdefghjklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //建立隨機物件 Random rand = new Random(); //設定驗證碼圖片展示的寬高 int width = 100; int height = 30; //建立圖片緩衝物件 BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //獲取出作圖物件 Graphics graphics = img.getGraphics(); //設定背景顏色 graphics.setColor(Color.gray); //設定填充一個矩形 graphics.fillRect(0, 0, width, height); graphics.setColor(Color.black); //引數1,2是線條起點座標,3,4是線條終點座標 graphics.drawLine(5, 10, 100, 25); graphics.setColor(Color.blue); graphics.drawLine(10, 30, 100, 30); graphics.setColor(Color.red); graphics.drawLine(15, 15, 100, 20); graphics.setColor(Color.white); graphics.drawLine(20, 10, 100, 18); for (int i = 0; i < 4; i++) { graphics.setColor(Color.black); int nextInt = rand.nextInt(str.length()); String substring = str.substring(nextInt, nextInt+1); //填充文字及文字所在的xy座標的起點 graphics.drawString(substring, width/5*(i+1), 15); } //輸出 ImageIO.write(img, "jpg", resp.getOutputStream());
通過上邊的方法可以派生出加減乘除的驗證碼:將隨機字元全部改為數字(0-9),新增加減乘除符號字串,
隨機獲取出數字和符號即可