Java实现中文算数验证码(算数运算+-*/)

为了防止,页面向数据库暴力注册入力,用户登录暴力破解,所以加入验证码,验证码无法被软件获取上边的内容(加入算数计算,更加安全),所以在现在技术,暂时安全。

先看效果图:

第一次加载比较慢,防止无法加载验证码显示,后台获取准备好的默认正在加载图片(静态图片),后台图片获取好后,替代。


验证码效果图:

              

后台Java图片实现类VerificationCodeTool:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.tsXs.fileshare.tools;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.image.BufferedImage;  
  8. import java.util.HashMap;  
  9. import java.util.Map;  
  10. import java.util.Random;  
  11. import org.apache.log4j.Logger;  
  12.   
  13. /** 
  14.  *  
  15.  * ClassName: VerificationCodeTool <br/> 
  16.  * Description: creat verification code <br/> 
  17.  * Date: 2015-3-3 下午08:37:55 <br/> 
  18.  * <br/> 
  19.  *  
  20.  * @author yptian@aliyun.com 
  21.  *  
  22.  * first made 
  23.  * @version 1.0.0<br/> 
  24.  * 
  25.  */  
  26. public class VerificationCodeTool {  
  27.     //LOG  
  28.     private static final Logger LOG =Logger.getLogger(VerificationCodeTool.class);  
  29.     //verification code image width  
  30.     private static final int IMG_WIDTH=146;  
  31.     //verification code image height  
  32.     private static final int IMG_HEIGHT=30;  
  33.     //The number of interference lines  
  34.     private static final int DISTURB_LINE_SIZE = 15;  
  35.     //generate a random number  
  36.     private Random random = new Random();  
  37.     //result  
  38.     private int xyresult;  
  39.     //result random string  
  40.     private String randomString;  
  41.     //Chinese Numbers  
  42. //  private static final String [] CNUMBERS = "零,一,二,三,四,五,六,七,八,九,十".split(",");  
  43.     //零一二三四五六七八九十乘除加减  
  44.     //Here, must be java Unicode code  
  45.     private static final String CVCNUMBERS = "\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u4E58\u9664\u52A0\u51CF";  
  46.     //Definition of drawings in the captcha characters font, font name, font style, font size  
  47.     //static final font : In Chinese characters garbled  
  48.     private final Font font = new Font("黑体", Font.BOLD, 18);  
  49.     //data operator  
  50.     private static final Map<String, Integer> OPMap = new HashMap<String, Integer>();  
  51.       
  52.     static{  
  53.         OPMap.put("*"11);  
  54.         OPMap.put("/"12);  
  55.         OPMap.put("+"13);  
  56.         OPMap.put("-"14);  
  57.     }  
  58.     /** 
  59.      * The generation of image  verification code 
  60.      * */  
  61.     public BufferedImage drawVerificationCodeImage(){  
  62.         //image  
  63.         BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);  
  64.         //In memory to create a brush  
  65.         Graphics g = image.getGraphics();  
  66.         //Set the brush color  
  67. //      g.setColor(getRandomColor(200,250));  
  68.         g.setColor(Color.WHITE);  
  69.         //Fill the background color, using the current brush colour changing background color images  
  70.         //The meaning of the four parameters respectively, starting x coordinates, starting y, width, height.  
  71.         //image background  
  72.         g.fillRect(00, IMG_WIDTH, IMG_HEIGHT);  
  73.         //Set the brush color  
  74.         g.setColor(getRandomColor(200,250));  
  75.         //image border  
  76.         g.drawRect(00, IMG_WIDTH-2, IMG_HEIGHT-2);  
  77.           
  78.         //Set disturb line color  
  79.         g.setColor(getRandomColor(110133));  
  80.         //Generate random interference lines  
  81.         for(int i =0;i < DISTURB_LINE_SIZE; i++){  
  82.             drawDisturbLine1(g);  
  83.             drawDisturbLine2(g);  
  84.         }  
  85.         //Generate a random number, set return data  
  86.         getRandomMathString();  
  87.         LOG.info("验证码 : "+randomString);  
  88.         LOG.info("验证码结果 : "+xyresult);  
  89.         //The generated random string used to save the system  
  90.         StringBuffer logsu = new StringBuffer();  
  91.         for(int j=0,k = randomString.length(); j < k; j++){  
  92.           int chid = 0;  
  93.           if(j==1){  
  94.               chid = OPMap.get(String.valueOf(randomString.charAt(j)));  
  95.           }else{  
  96.               chid = Integer.parseInt(String.valueOf(randomString.charAt(j)));  
  97.           }  
  98.           String ch = String.valueOf(CVCNUMBERS.charAt(chid));  
  99.           logsu.append(ch);  
  100.           drawRandomString((Graphics2D)g,ch, j);  
  101.         }  
  102.         //= ?  
  103.         drawRandomString((Graphics2D)g,"\u7B49\u4E8E\uFF1F"3);  
  104.         logsu.append("\u7B49\u4E8E \uFF1F");  
  105.         LOG.info("汉字验证码 : "+logsu);  
  106.         randomString = logsu.toString();  
  107.         //Release the brush object  
  108.         g.dispose();  
  109.         return image;  
  110.     }  
  111.     /** 
  112.      * Get a random string 
  113.      * */  
  114.     private void getRandomMathString(){  
  115.         //Randomly generated number 0 to 10  
  116.         int xx = random.nextInt(10);  
  117.         int yy = random.nextInt(10);  
  118.         //save getRandomString  
  119.         StringBuilder suChinese =  new StringBuilder();  
  120.             //random 0,1,2  
  121.             int Randomoperands = (int) Math.round(Math.random()*2);  
  122.             //multiplication  
  123.             if(Randomoperands ==0){  
  124.                 this.xyresult = yy * xx;  
  125. //              suChinese.append(CNUMBERS[yy]);  
  126.                 suChinese.append(yy);  
  127.                 suChinese.append("*");  
  128.                 suChinese.append(xx);  
  129.             //division, divisor cannot be zero, Be divisible  
  130.             }else if(Randomoperands ==1){  
  131.                 if(!(xx==0) && yy%xx ==0){  
  132.                     this.xyresult = yy/xx;  
  133.                     suChinese.append(yy);  
  134.                     suChinese.append("/");  
  135.                     suChinese.append(xx);  
  136.                 }else{  
  137.                     this.xyresult = yy + xx;  
  138.                     suChinese.append(yy);  
  139.                     suChinese.append("+");  
  140.                     suChinese.append(xx);  
  141.                 }  
  142.             //subtraction  
  143.             }else if(Randomoperands ==2){  
  144.                     this.xyresult = yy - xx;  
  145.                     suChinese.append(yy);  
  146.                     suChinese.append("-");  
  147.                     suChinese.append(xx);  
  148.             //add  
  149.             }else{  
  150.                     this.xyresult = yy + xx;  
  151.                     suChinese.append(yy);  
  152.                     suChinese.append("+");  
  153.                     suChinese.append(xx);  
  154.             }  
  155.         this.randomString = suChinese.toString();  
  156.     }  
  157.     /** 
  158.      * Draw a random string 
  159.      * @param g Graphics 
  160.      * @param randomString random string 
  161.      * @param i the random number of characters 
  162.      * */  
  163.     public void drawRandomString(Graphics2D g,String randomvcch,int i){  
  164.         //Set the string font style  
  165.         g.setFont(font);  
  166.         //Set the color string  
  167.         int rc = random.nextInt(255);  
  168.         int gc = random.nextInt(255);  
  169.         int bc = random.nextInt(255);  
  170.         g.setColor(new Color(rc, gc, bc));  
  171.         //random string  
  172.         //Set picture in the picture of the text on the x, y coordinates, random offset value  
  173.         int x = random.nextInt(3);  
  174.         int y = random.nextInt(2);  
  175.         g.translate(x, y);  
  176.         //Set the font rotation angle  
  177.         int degree = new Random().nextInt() % 15;  
  178.         //Positive point of view  
  179.         g.rotate(degree * Math.PI / 1805+i*2520);  
  180.         //Character spacing is set to 15 px  
  181.         //Using the graphics context of the current font and color rendering by the specified string for a given text.  
  182.         //The most on the left side of the baseline of the characters in the coordinate system of the graphics context (x, y) location  
  183.         //str- to draw string.x - x coordinate.y - y coordinate.  
  184.         g.drawString(randomvcch, 5+i*2520);  
  185.         //Reverse Angle  
  186.         g.rotate(-degree * Math.PI / 1805+i*2520);  
  187.     }  
  188.     /** 
  189.      *Draw line interference  
  190.      *@param g Graphics 
  191.      * */  
  192.     public void drawDisturbLine1(Graphics g){  
  193.         int x1 = random.nextInt(IMG_WIDTH);  
  194.         int y1 = random.nextInt(IMG_HEIGHT);  
  195.         int x2 = random.nextInt(13);  
  196.         int y2 = random.nextInt(15);  
  197.         //x1 - The first point of the x coordinate.  
  198.         //y1 - The first point of the y coordinate  
  199.         //x2 - The second point of the x coordinate.  
  200.         //y2 - The second point of the y coordinate.  
  201.         //X1 and x2 is the starting point coordinates, x2 and y2 is end coordinates.  
  202.         g.drawLine(x1, y1, x1 + x2, y1 + y2);  
  203.     }  
  204.       
  205.     /** 
  206.      *Draw line interference  
  207.      *@param g Graphics 
  208.      * */  
  209.     public void drawDisturbLine2(Graphics g){  
  210.         int x1 = random.nextInt(IMG_WIDTH);  
  211.         int y1 = random.nextInt(IMG_HEIGHT);  
  212.         int x2 = random.nextInt(13);  
  213.         int y2 = random.nextInt(15);  
  214.         //x1 - The first point of the x coordinate.  
  215.         //y1 - The first point of the y coordinate  
  216.         //x2 - The second point of the x coordinate.  
  217.         //y2 - The second point of the y coordinate.  
  218.         //X1 and x2 is the starting point coordinates, x2 and y2 is end coordinates.  
  219.         g.drawLine(x1, y1, x1 - x2, y1 - y2);  
  220.     }  
  221.     /** 
  222.      * For random color 
  223.      * @param fc fc 
  224.      * @param bc bc 
  225.      * @return color random color 
  226.      * */  
  227.     public Color getRandomColor(int fc,int bc){  
  228.         if(fc > 255){  
  229.             fc = 255;  
  230.         }  
  231.         if(bc > 255){  
  232.             bc = 255;  
  233.         }  
  234.         //Generate random RGB trichromatic  
  235.         int r = fc+random.nextInt(bc -fc - 16);  
  236.         int g = fc+random.nextInt(bc - fc - 14);  
  237.         int b = fc+random.nextInt(bc - fc - 18);  
  238.         return new Color(r, g, b);  
  239.     }  
  240.       
  241.     /** 
  242.      * xyresult.<br/> 
  243.      * 
  244.      * @return  the xyresult <br/> 
  245.      *  
  246.      */  
  247.     public int getXyresult() {  
  248.         return xyresult;  
  249.     }  
  250.       
  251.     /** 
  252.      * randomString.<br/> 
  253.      * 
  254.      * @return  the randomString <br/> 
  255.      *  
  256.      */  
  257.     public String getRandomString() {  
  258.         return randomString;  
  259.     }  
  260.       
  261. }  
生产静态验证码(为了防止,加载慢,空白显示):

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.tsXs.fileshare.tools;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Graphics;  
  5. import java.awt.Graphics2D;  
  6. import java.awt.image.BufferedImage;  
  7. import java.io.BufferedOutputStream;  
  8. import java.io.File;  
  9. import java.io.FileOutputStream;  
  10.   
  11. import javax.imageio.ImageIO;  
  12. import javax.swing.ImageIcon;  
  13. import javax.swing.filechooser.FileSystemView;  
  14.   
  15. import org.apache.log4j.Logger;  
  16.   
  17. import com.tsXs.fileshare.configuration.properties.StaticConstants;  
  18.  /** 
  19.  * ClassName: ImageTool <br/> 
  20.  * Description: get BufferedImage creat image<br/> 
  21.  * Date: 2015-3-10 下午05:05:38 <br/> 
  22.  * <br/> 
  23.  *  
  24.   * @author yptian@aliyun.com 
  25.   *  
  26.   * first made 
  27.   * @version 1.0.0<br/> 
  28.   * 
  29.   */  
  30. public class ImageTool {  
  31.     //LOG  
  32.     private static final Logger LOG = Logger.getLogger(ImageTool.class);  
  33.     //image  
  34.     private BufferedImage image;     
  35.       
  36.     /** 
  37.      * createImage : out dest path for image 
  38.      * @param fileLocation dest path 
  39.      */  
  40.     private void createImage(String fileLocation) {          
  41.         try {              
  42.             FileOutputStream fos = new FileOutputStream(fileLocation);              
  43.             BufferedOutputStream bos = new BufferedOutputStream(fos);    
  44.             ImageIO.write(image, "png", bos);  
  45. //            com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(bos);              
  46. //            encoder.encode(image);              
  47.             bos.flush();  
  48.             bos.close();   
  49.             LOG.info("@2"+fileLocation+"图片生成输出成功");     
  50.        } catch (Exception e) {              
  51.             LOG.info("@2"+fileLocation+"图片生成输出失败",e);      
  52.        }  
  53.     }  
  54.     /** 
  55.      * createFileIconImage :create share file list icon 
  56.      * @param destOutPath  create file icon save dictory  
  57.      */  
  58.     public void createFileIconImage(String destOutPath){  
  59.          //get properties operate tool  
  60.          PropertiesTool propertiesTool = PropertiesTool.getInstance(StaticConstants.SHARE_FILE_CONFGURATION_PROPERTIES_PATH);  
  61.          //get share file root path  
  62.          String shareFileRootPath = propertiesTool.getPropertiesValue("FileShareRootPath");  
  63.          //root dictory  
  64.          File rootDictory = new File(shareFileRootPath);  
  65.          //child file list  
  66.          File [] fileList = rootDictory.listFiles();  
  67.          //child list files  
  68.          File file = null;  
  69.          if(fileList != null && fileList.length>0){  
  70.              LOG.info("分享文件根目录下文件数:"+fileList.length);  
  71.              for(int i = 0,j = fileList.length;i < j;i++){  
  72.                  String fileName = fileList[i].getName();  
  73.                  String fileAllName = shareFileRootPath +fileName;  
  74.                  file = new File(fileAllName);  
  75.                  //get file system icon  
  76.                  ImageIcon fileIcon = (ImageIcon) FileSystemView.getFileSystemView().getSystemIcon(file);  
  77.                  image = (BufferedImage) fileIcon.getImage();  
  78.                  if(image != null){  
  79.                      LOG.info("@1"+fileName+"文件的图标获取成功");  
  80.                  }  
  81.                  Graphics g = image.getGraphics();  
  82.                  g.drawImage(image, 00null);  
  83.                  String fileNameX = fileName.substring(0,fileName.lastIndexOf("."));  
  84.                  //out image to dest  
  85.                  createImage(destOutPath+"\\"+fileNameX+".png");  
  86.                  LOG.info("@3"+fileName+"文件的图标生成成功");  
  87.              }  
  88.          }  
  89.     }  
  90.       
  91.     /** 
  92.      * creatDefaultVerificationCode :create default verification code 
  93.      * @param destOutPath  create creatDefaultVerificationCode save dictory  
  94.      */  
  95.     public void creatDefaultVerificationCode(String destOutPath){  
  96.         //verification code image height  
  97.         //comment to com.tss.fileshare.tools.VerificationCodeTool  65 row,please  
  98.         int imgwidth=146;  
  99.         int imgheight=30;  
  100.         int disturblinesize = 15;  
  101.         VerificationCodeTool vcTool = new VerificationCodeTool();  
  102.         //default verification code  
  103.          image = new BufferedImage(imgwidth, imgheight, BufferedImage.TYPE_INT_RGB);  
  104.         Graphics g = image.getGraphics();  
  105.         g.setColor(Color.WHITE);  
  106.         g.fillRect(0014630);  
  107.         g.setColor(vcTool.getRandomColor(200,250));  
  108.         g.drawRect(00, imgwidth-2, imgheight-2);  
  109.         for(int i =0;i < disturblinesize; i++){  
  110.             vcTool.drawDisturbLine1(g);  
  111.             vcTool.drawDisturbLine2(g);  
  112.         }  
  113.         //玩命加载中…  
  114.         String defaultVCString = "\u73A9\u547D\u52A0\u8F7D\u4E2D\u2026";  
  115.         String dfch = null;  
  116.         for(int i = 0;i < 6;i++){  
  117.             dfch = String.valueOf(defaultVCString.charAt(i));  
  118.             vcTool.drawRandomString((Graphics2D)g, dfch, i);  
  119.         }  
  120.         LOG.info("默然验证码生成成功");  
  121. //      Graphics gvc = imagevc.getGraphics();  
  122.         createImage(destOutPath+"\\defaultverificationcode.jpeg");  
  123.     }  
  124.    /** 
  125.     * graphicsGeneration : create image 
  126.     * @param imgurl display picture url . eg:F:/imagetool/7.jpg<br/> 
  127.     * @param imageOutPathName image out path+naem .eg:F:\\imagetool\\drawimage.jpg<br/> 
  128.     * @param variableParmeterLength ; int, third parameter length.<br/> 
  129.     * @param drawString variableParmeterLength ;String [] .<br/> 
  130.     */  
  131.     public void graphicsGeneration(String imgurl,String imageOutPathName,int variableParmeterLength,String...drawString) {  
  132.         //The width of the picture  
  133.         int imageWidth = 500;     
  134.         //The height of the picture  
  135.         int imageHeight = 400;     
  136.         image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);          
  137.         Graphics graphics = image.getGraphics();          
  138.         graphics.setColor(Color.WHITE);      
  139.         //drawing image  
  140.         graphics.fillRect(00, imageWidth, imageHeight);          
  141.         graphics.setColor(Color.BLACK);          
  142.         //draw string  string , left margin,top margin  
  143.         for(int i = 0,j = variableParmeterLength;i < j;i++){  
  144.             graphics.drawString(drawString[i], 5010+15*i);  
  145.         }  
  146.         //draw image url  
  147.         ImageIcon imageIcon = new ImageIcon(imgurl);   
  148.         //draw image , left margin,top margin  
  149.         //The coordinates of the top left corner as the center(x,y)[left top angle]  
  150.         //Image observer :If img is null, this method does not perform any action  
  151.         graphics.drawImage(imageIcon.getImage(), 2000null);   
  152.         createImage(imageOutPathName);      
  153.     }  
  154.   
  155.     public BufferedImage getImage() {  
  156.         return image;  
  157.     }  
  158.     public void setImage(BufferedImage image) {  
  159.         this.image = image;  
  160.     }  
  161. }  
服务器,启动的时候,调用一次,生成默认图片到服务器“/servertempdictory/fileicon/”目录下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //create default verification code  
  2. String  fileIconDictory = serverPath+"\\servertempdictory\\fileicon";  
  3.  imageTool.creatDefaultVerificationCode(fileIconDictory);  
生成动态验证码,并保存值到session中(此处有登录和注册的分路,这个读者可忽略,走一条既可):

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.     * creat verification code 
  3.     * */  
  4.    public void verificationcode(){  
  5.      //response  
  6.      HttpServletResponse response = ServletActionContext.getResponse();  
  7.      //request  
  8.      HttpServletRequest request = ServletActionContext.getRequest();  
  9.      //verification code demander  
  10.      String vCdemander = request.getParameter("vcdemander");  
  11.      try{  
  12.        //set encoding  
  13.        request.setCharacterEncoding("utf-8");  
  14.        response.setContentType("text/html;charset=utf-8");  
  15.        //Verification code tool  
  16.        VerificationCodeTool vcTool = new VerificationCodeTool();  
  17.        BufferedImage image = vcTool.drawVerificationCodeImage();  
  18.        //Verification code result  
  19.        int vcResult = vcTool.getXyresult();  
  20.        String vcValue = vcTool.getRandomString();  
  21.     //Set ban cache  
  22.     //Cache-control : Specify the request and response following caching mechanism  
  23.     //no-cache: Indicates a request or response message cannot cache  
  24.     response.setHeader("Cache-Control""no-cache");  
  25.     //Entity header field response expiration date and time are given  
  26.     response.setHeader("Pragma""No-cache");  
  27.     response.setDateHeader("Expires"0);  
  28.     // Set the output stream content format as image format  
  29.     response.setContentType("image/jpeg");  
  30.     //session  
  31.     //true: if the session exists, it returns the session, or create a new session.  
  32.     //false: if the session exists, it returns the session, otherwise it returns null.  
  33.     HttpSession session=request.getSession(true);    
  34.     //set verificationcode to session  
  35.     //login  
  36.     if("userlogin".equals(vCdemander)){  
  37.         session.setAttribute("verificationcodeuserlogin",vcResult);  
  38.     }  
  39.     //regiser  
  40.     if("userregister".equals(vCdemander)){  
  41.         session.setAttribute("verificationcodeuserregister",vcResult);  
  42.     }  
  43.     //To the output stream output image  
  44.     ImageIO.write(image, "JPEG", response.getOutputStream());  
  45.     LOG.info("获取验证码成功 :\n验证码:"+vcValue+"\n验证码结果:"+vcResult);  
  46. catch (Exception e) {  
  47.     LOG.error("获取验证码失败",e);  
  48. }  
  49.  }  
用struts2实现,所以配置文件struts.xml:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <!-- Set whether to support dynamic method calls, true to support, false does not support. -->  
  2. <constant name="struts.enable.DynamicMethodInvocation" value="true" />  
  3. <!-- The suffix specified request -->  
  4. <constant name="struts.action.extension" value="do,go,tsXs,action"></constant>  
  5. <!-- user operation [first login server,server initialize]-->  
  6. <package name="user" namespace="/fileshare" extends="struts-default">  
  7.     <!-- user operate ; The wildcard method call-->  
  8.     <action name="user*" class="com.tsXs.fileshare.controller.UserController" method="{1}">  
  9.         <result name="success">/view/common/message.jsp</result>  
  10.         <result name="error">/view/userLogin.jsp</result>  
  11.     </action>  
  12. </package>  

页面jsp显示代码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <tr>  
  2.   <td width="100">  
  3.     <span class="hint">*[验证码]:只能输入数字和负号"-"</span>  
  4.   </td>  
  5. </tr>  
  6. <tr>  
  7.   <td width="100">  
  8.     <label for="userRegPassWord">验证码</label>  
  9.           <input type="text" id="verificationcodereg" name="verificationcodereg" tabindex="3" maxlength="3" class="t_input" value="" style="ime-mode:disabled;"  οnblur="checkuserverificationcode(this);" οnkeypress="return (/[\d-]/.test(String.fromCharCode(event.keyCode)));"  />  
  10.          <span id="usvcmsg"></span>  
  11.         <input type="hidden" id="verificationcoderegflag" value="" />  
  12.   </td>  
  13. </tr>  
  14. <tr>  
  15.   <td width="140">  
  16.     <div id="refreshvc">  
  17.     <span οnclick="refreshvc();" style="padding-left: 49px;cursor: pointer;"><img id="verificationcodeimg" src="${pageContext.request.contextPath}/servertempdictory/fileicon/defaultverificationcode.jpeg" />  
  18.     <span style="height: 30px;width: 16px;padding-left: 4px;"><img src="image/refreshvc.png" /></span>  
  19.     <span style="font-size: 12px;color:#2c629e; width: 20px;">换一张</span>  
  20.     </span>  
  21.     </div>  
  22.   </td>  
  23. </tr>  

在js中用正则,保证只能输入,最多3位,可以在数字前输入一个"-",即onkeypress保证只能输入数字和"-":

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var userverificationcoderegex = /^(-{0,1}\d+){1,3}$/;  
  2. if(userverificationcoderegex.test(userverificationcode)){.....  
jsp图片效果:


js动态刷新验证码:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $(document).ready(function(){  
  2.     //load verificatino code  
  3.     refreshvc();  
  4. });  
  5. //refresh verification code  
  6. function refreshvc(){  
  7.     var path = $("#contextPath").val();  
  8.     var refreshvcurl =path+"/fileshare/userverificationcode.tsXs?vcdemander=userregister&time="+new Date();  
  9.     $("#verificationcodeimg").attr("src",refreshvcurl);  
  10. }  
验证码验证:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * checkverificationcode  : check verification code equals 
  3.  */  
  4. ublic void checkverificationcode(){  
  5.    //request  
  6.    HttpServletRequest request = ServletActionContext.getRequest();  
  7.    //response  
  8.    HttpServletResponse response = ServletActionContext.getResponse();  
  9.    //output stream  
  10.    PrintWriter out = null;  
  11.    //session  
  12.    HttpSession session = request.getSession();  
  13.    //verification code from client  
  14.    String vcclient = null;  
  15.    //verification code from server  
  16.    String vcserver = null;  
  17.    //verification code demander  
  18.    String vCdemander = request.getParameter("vcdemander");  
  19.    //check verification code to clien flag  
  20.    String checktoclienflag = null;  
  21.    try{  
  22.     //get verificationcode to session  
  23.     //login  
  24.     if("userlogin".equals(vCdemander)){  
  25.         vcclient = request.getParameter("vclogincode");  
  26.         vcserver = String.valueOf(session.getAttribute("verificationcodeuserlogin"));  
  27.     }  
  28.     //regiser  
  29.     if("userregister".equals(vCdemander)){  
  30.         vcclient = request.getParameter("vcregcode");  
  31.         vcserver = String.valueOf(session.getAttribute("verificationcodeuserregister"));  
  32.     }  
  33.      vcclient = UserController.encodingconvert(vcclient);  
  34.      vcclient = vcclient == null ? "" : vcclient;  
  35.      if(vcclient.equals(vcserver)){  
  36.          checktoclienflag = "vcok";  
  37.      }else{  
  38.          checktoclienflag = "vcwrong";  
  39.      }  
  40.        //set no cache,content type ,encoding  
  41.        response.setHeader("Cache-Control""no-cache");  
  42.        response.setContentType("text/html");  
  43.        response.setCharacterEncoding("GBK");  
  44.        //output stream  
  45.        out = response.getWriter();  
  46.        out.print(checktoclienflag);  
  47.        LOG.info("验证码:vcclient: "+vcclient+"vcserver: "+vcserver+"验证顺利");  
  48.    }catch (Exception e) {  
  49.        LOG.error("vcclient: "+vcclient+"vcserver: "+vcserver+"验证失败",e);  
  50.    }finally{  
  51.        out.flush();  
  52.        out.close();  
  53.    }  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. properties辅助类:  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <pre class="java" name="code">/** 
  2.  * Copyright (c) 2015,TravelSky.  
  3.  * All Rights Reserved. 
  4.  * TravelSky CONFIDENTIAL 
  5.  *  
  6.  * Project Name:filesharetss 
  7.  * Package Name:com.tss.fileshare.controller.tools 
  8.  * File Name:PropertiesFileOperation.java 
  9.  * Date:2015-2-27 下午05:30:05 
  10.  *  
  11.  */  
  12. package com.tsXs.fileshare.tools;  
  13.   
  14. import java.io.FileInputStream;  
  15. import java.io.FileNotFoundException;  
  16. import java.io.FileOutputStream;  
  17. import java.io.IOException;  
  18. import java.io.InputStream;  
  19. import java.io.OutputStream;  
  20. import java.util.Enumeration;  
  21. import java.util.Properties;  
  22.   
  23. import org.apache.log4j.Logger;  
  24.   
  25. /** 
  26.  *  
  27.  * ClassName: PropertiesFileOperationTool <br/> 
  28.  * Description: inner class Properties file operation <br/> 
  29.  * Date: 2015-2-27 下午05:10:52 <br/> 
  30.  * <br/> 
  31.  *  
  32.  * @author yptian@aliyun.com 
  33.  *  
  34.  *         first made 
  35.  * @version 1.0.0<br/> 
  36.  *  
  37.  */  
  38.   
  39. public class PropertiesTool {  
  40.     // LOG  
  41.     private static final Logger LOG = Logger.getLogger(PropertiesTool.class);  
  42.     // Singleton instance  
  43.     private static PropertiesTool instance = new PropertiesTool();  
  44.       
  45.     private static Properties properties;  
  46.     /** 
  47.      *  
  48.      * Creates a new Singleton instance of PropertiesFileOperation.<br/> 
  49.      */  
  50.     private PropertiesTool() {  
  51.           
  52.     }  
  53.     /** 
  54.      * getInstance :get properties object  
  55.      * @param propertiesFilePathName properties file path and name 
  56.      * @return 
  57.      */  
  58.     public static PropertiesTool getInstance(String propertiesFilePathName){  
  59.         properties = loadPropertiesFile(propertiesFilePathName);  
  60.         return instance;  
  61.     }  
  62.     /** 
  63.      *  
  64.      * loadPropertiesFile:Load properties file by  path and name<br/> 
  65.      * @param propertiesFilePathName path and name of properties file <br/> 
  66.      * @return properties properties  
  67.      */  
  68.     private static Properties loadPropertiesFile(String propertiesFilePathName) {  
  69.         Properties properties = new Properties();  
  70.         InputStream isLoad = PropertiesTool.class.getClassLoader().getResourceAsStream(propertiesFilePathName);  
  71.         try {  
  72.             // loader properties  
  73.             properties.load(isLoad);  
  74.         } catch (IOException e) {  
  75.             LOG.error(propertiesFilePathName + " properties file read failure", e);  
  76.         } finally {  
  77.             try {  
  78.                 isLoad.close();  
  79.             } catch (IOException e) {  
  80.                 LOG.error("properties file stream close error",e);  
  81.             }  
  82.         }  
  83.         return properties;  
  84.     }  
  85.     /** 
  86.      * * 
  87.      * getPropertiesValue:Get properties value by key <br/> 
  88.      * @param key properties key  <br/> 
  89.      * @return value properties value 
  90.      */  
  91.     public String getPropertiesValue(String key) {  
  92.         return properties.getProperty(key);  
  93.     }  
  94.       
  95.       
  96.     public static String getInstanceByServerRealPathOfValue(String propertiesFileServerRealPathName,String key){  
  97.         String pValue = null;  
  98.         try {  
  99.                 InputStream isrLoad = new FileInputStream(propertiesFileServerRealPathName);  
  100.                 properties.load(isrLoad);  
  101.                 isrLoad.close();  
  102.                 pValue =  properties.getProperty(key);  
  103.             } catch (IOException e) {  
  104.                 LOG.error("Failed to get the value under the server of the properties file",e);  
  105.             }  
  106.         return pValue;  
  107.     }  
  108.     /** 
  109.      *  
  110.      * getProperties:Get properties by key and value <br/> 
  111.      * @param key properties key  <br/> 
  112.      * @param value  properties value 
  113.      */  
  114.     public void setProperties(String filePath,String key,String value){  
  115.         try {  
  116.             InputStream is = new FileInputStream(filePath);  
  117.             OutputStream os = new FileOutputStream(filePath);  
  118.             properties.load(is);  
  119.             properties.setProperty(key, value);  
  120.             properties.store(os, null);  
  121.             os.flush();  
  122.             is.close();  
  123.             os.close();  
  124.         } catch (IOException e) {  
  125.             LOG.error("properties file stream close error",e);  
  126.         }  
  127.     }  
  128.       
  129.     /** 
  130.      *  
  131.      * alterProperties:alter properties by key and value <br/> 
  132.      * @param key properties key  <br/> 
  133.      * @param value  properties value 
  134.      */  
  135.     public void alterProperties(String filePath,String key,String value){  
  136.         try{  
  137.             InputStream is = new FileInputStream(filePath);  
  138.             OutputStream os = new FileOutputStream(filePath);  
  139.             properties.load(is);  
  140.             properties.remove(key);  
  141.             properties.setProperty(key, value);  
  142.             properties.store(os, null);  
  143.             os.flush();  
  144.             is.close();  
  145.             os.close();  
  146.         } catch (IOException e) {  
  147.             LOG.error("properties file stream close error",e);  
  148.         }  
  149.     }  
  150.     /** 
  151.      *  
  152.      * getAllProperties:Read the properties of all the information <br/> 
  153.      * @return properties information 
  154.      */  
  155.     @SuppressWarnings("rawtypes")  
  156.     public String getAllProperties(){  
  157.         Enumeration en = properties.propertyNames();  
  158.         StringBuffer sf = new StringBuffer();  
  159.         while (en.hasMoreElements()) {  
  160.            String key = (String) en.nextElement();  
  161.            String value = properties.getProperty (key);  
  162.            sf.append("\n"+key);  
  163.            sf.append("=");  
  164.            value = value.replace(":""\\:");  
  165.            sf.append(value);  
  166.         }  
  167.         return sf.toString();  
  168.     }  
  169.   
  170. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值