代碼實現一個簡單的生成隨機驗證碼的小程序
- //隨機生成驗證碼
- //第一步:
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- test(response);
- }
- private void test(HttpServletResponse response) throws IOException {
- int width = 120,height=25;
- //生成一張圖片 此時得到一張寬120,長25的一張黑色圖片
- BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- Graphics grap = img.getGraphics();//得到一個畫筆
- //填充背景色
- grap.setColor(Color.pink);
- //設置填充的區域
- grap.fillRect(1, 1, width-2, height-2);
- //設置邊框的顏色 同填充背景顏色 靠近誰是設置哪個屬性的顏色
- grap.setColor(Color.red);
- grap.drawRect(0, 0, width-1, height-1);
- //設置字體
- grap.setFont(new Font("黑體", Font.BOLD|Font.ITALIC, 18));
- //向圖片上寫字 嘿嘿隨機生成了字符串
- Random r = new Random();
- int p = 15;
- for(int i=1;i<=4;i++)
- {
- grap.drawString(r.nextInt(10)+"", p,20);
- p+=15;
- }
- //向圖片上畫線
- for(int i=1;i<=10;i++)
- {
- grap.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
- }
- //把圖片發送給客戶端
- ImageIO.write(img, "jpg", response.getOutputStream());
- }
- //第二部:新建login.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>login.html</title>
- <script type="text/javascript">
- function ff(){
- var img = document.getElementById("image");
- img.src="/day33_response/demo4?user=1"+new Date().getTime();
- // img.setAttribute("src","/day33_response/demo4?user="+new Date().getTime());
- }
- </script>
- </head>
- <body>
- <form action="#" method="get">
- 用戶名<input type="text" name="uname"><br/><br/>
- 密 碼<input type="password" name="pwd"><br/><br/>
- 驗證碼<input type="text" name="code">
- <!-- 如果image沒有寫src頁面剛加載時沒有東西,刷新之后才會顯示驗證碼圖片 -->
- <img id="image" src='/day33_response/demo4'>
- <!-- 換兩行 -->
- <a href="javascript:ff()">換一張</a><br/> <br/>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
- // 大功告成就可以發布到tomcat上瀏覽了
- //此處介紹一種懶人方法,在doGet方法中,其中ValidateCode四個函數分別是矩形的寬、高以及驗證碼的個數和干擾線的條數,然后第一步的函數就可統統省略了
- ValidateCode code = new ValidateCode(320, 25, 4, 8);
- code.write(response.getOutputStream());
- //注:導相應的ValidateCode的JAR包喔。
新聞熱點
疑難解答