簡單 驗證碼 功能

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   color   

在貼代碼之前首先簡述一下驗證驗證碼原理:隨機擷取驗證碼的值,把這個值存到session中,其作用可想而知就是要拿來跟前台資料作比較,通過Graphics將值進行模糊處理之後傳到前台頁面展示。

  1 package com.skss.util;  2   3   4 import java.awt.Color;  5 import java.awt.Font;  6 import java.awt.Graphics;  7 import java.awt.image.BufferedImage;  8 import java.io.IOException;  9 import java.util.Random; 10  11 import javax.imageio.ImageIO; 12 import javax.servlet.ServletException; 13 import javax.servlet.ServletOutputStream; 14 import javax.servlet.http.HttpServlet; 15 import javax.servlet.http.HttpServletRequest; 16 import javax.servlet.http.HttpServletResponse; 17 import javax.servlet.http.HttpSession; 18  19 @SuppressWarnings("serial") 20 public class ValidateCodeServlet extends HttpServlet { 21     char[] codeSequence={‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, 22             ‘K‘, ‘L‘, ‘M‘, ‘N‘, ‘O‘, ‘P‘, ‘Q‘, ‘R‘, ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, 23             ‘X‘, ‘Y‘, ‘Z‘, ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘ }; 24     public ValidateCodeServlet() { 25         super(); 26     } 27  28     public void destroy() { 29         super.destroy();  30     } 31  32     public void doGet(HttpServletRequest request, HttpServletResponse response) 33             throws ServletException, IOException { 34         this.doPost(request, response); 35     } 36      37     public void doPost(HttpServletRequest request, HttpServletResponse response) 38             throws ServletException, IOException { 39         String params = request.getParameter("parame"); 40         response.setContentType("image/jpeg");   41         response.setHeader("Pragma","No-cache");   42         response.setHeader("Cache-Control","no-cache");   43         response.setDateHeader("Expires", 0);         44         HttpSession session=request.getSession();   45         // 在記憶體中建立圖象   46         int width=60, height=20;   47         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   48         // 擷取圖形上下文   49         Graphics g = image.getGraphics();   50         //產生隨機類   51         Random random = new Random();   52         // 設定背景色   53         g.setColor(getRandColor(200,250));   54         g.fillRect(0, 0, width, height);   55         //設定字型   56         g.setFont(new Font("Times New Roman",Font.PLAIN,18));   57         //畫邊框   58         //g.setColor(new Color());   59         //g.drawRect(0,0,width-1,height-1);   60         // 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程式探測到   61         g.setColor(getRandColor(160,200));   62         for (int i=0;i<155;i++) {   63             int x = random.nextInt(width);   64             int y = random.nextInt(height);   65             int xl = random.nextInt(12);   66             int yl = random.nextInt(12);   67             g.drawLine(x,y,x+xl,y+yl);   68         }   69         // 取隨機產生的認證碼(4位元字)   70         String sRand="";   71         for (int i=0;i<4;i++){   72             String rand=String.valueOf(random.nextInt(10));   73              74             if(Integer.parseInt(rand)%2==0){ 75                 rand=codeSequence[random.nextInt(36)]+""; 76             } 77              78             sRand+=rand;   79             // 將認證碼顯示到圖象中   80             g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接產生   81             g.drawString(rand,13*i+6,16);   82         }   83         // 將認證碼存入SESSION   84         session.setAttribute(params,sRand);   85         // 圖象生效   86         g.dispose();   87         ServletOutputStream responseOutputStream =response.getOutputStream();   88         // 輸出圖象到頁面   89         ImageIO.write(image, "JPEG", responseOutputStream);   90         //以下關閉輸入資料流!   91         responseOutputStream.flush();   92         responseOutputStream.close();  93     } 94     Color getRandColor(int fc,int bc){//給定範圍獲得隨機顏色   95         Random random = new Random();   96         if(fc>255) fc=255;   97         if(bc>255) bc=255;   98         int r=fc+random.nextInt(bc-fc);   99         int g=fc+random.nextInt(bc-fc);  100         int b=fc+random.nextInt(bc-fc);  101         return new Color(r,g,b);  102     } 103 }
View Code

上面的代碼注釋想必已經描述的很清楚了,這裡就不細說了。注意String params = request.getParameter("parame");session.setAttribute(params,sRand); 這是關鍵

 1        <servlet> 2         <description>vCode</description> 3         <display-name>vCode</display-name> 4         <servlet-name>ValidateCodeServlet</servlet-name> 5         <servlet-class> 6             com.skss.util.ValidateCodeServlet 7         </servlet-class> 8     </servlet> 9     <servlet-mapping>10         <servlet-name>ValidateCodeServlet</servlet-name>11         <url-pattern>/vcode</url-pattern>12     </servlet-mapping>
View Code

web.xml代碼,下面是vcode.jsp頁面,後面的參數為了讓這個驗證碼通用,同時保正每個頁面的驗證碼不會因為其他引用的驗證碼重新整理而改變

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3     String path = request.getContextPath(); 4     String basePath = request.getScheme() + "://" 5             + request.getServerName() + ":" + request.getServerPort() 6             + path + "/"; 7     String type = request.getParameter("type"); 8 %> 9 <script>10 function refresh(){11     document.location.href = document.location.href;12 }13 </script>14 <img src="${path}/vcode?parame=<%= type%>" onclick="refresh()" style="cursor: pointer;" title="看不清!點擊換一個!"/>
View Code

下面是引用這個jsp的iframe

1 <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes" src="${path}/app/admin/login/vcode.jsp?type=login_vcode" style="width: 60px;height: 20px;padding: 0,0,0,0;" scrolling="no" ></iframe>
View Code
if (!user.getVcode().equalsIgnoreCase(                    (String) this.request.getSession().getAttribute("login_vcode"))) {                request.setAttribute("msg", "驗證碼錯誤!");                return "loginx";            }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.