首页 > 代码库 > 验证码选择加粗的数字案例

验证码选择加粗的数字案例

设计目的

  提高网站安全级别,防止非法扫描识别验证码

验证码效果图(访问地址:http://xxxx:xxxx/checkCode/userlogin.html

  技术分享

开发环境

  1.jdk1.7+tomcat

  2.springMVC框架(jar包如下)

  技术分享

  3.目录结构

   技术分享

 

代码

  1.web.xml配置 

    <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    2.applicationContext.xml配置

   <!-- 开启注解扫描 -->
   <context:component-scan base-package="controller"></context:component-scan>
   <!-- 开启Controller注解扫描 -->
   <mvc:annotation-driven/>

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="http://www.mamicode.com/"></property>
    <property name="suffix" value="http://www.mamicode.com/.html"></property>
   </bean>

   3.userlogin.html 

    <div style="text-align:center;margin-top:200px;">
      <input id="checkcode" name="checkcode" type="text" placeholder="选择加粗的数字" style="width:260px;height:30px;"/><br><br>
      <img id="imgCode" name="imgCode" src="http://www.mamicode.com/loginimg.do" onclick="this.src=http://www.mamicode.com/‘loginimg.do?m=‘+new Date().getTime()" style="cursor:  pointer;width:260px;height:50px;" title="点击刷新">
    </div>

   4.commons-zhzhair.properties配置

   技术分享

   5.propertiesValues.java读取参数

    public static String getString(Class<?> className,String type){
      Properties properties = new Properties();
      try {
        properties.load(className.getResourceAsStream("/commons-zhzhair.properties"));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      if("checkcodeStr".equals(type)){
        return properties.getProperty("checkcodeStr");
      }else if("checkcodeFace".equals(type)){
        return properties.getProperty("checkcodeFace");
      }else{
        try {
          throw new Exception("the key does not exit");
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        return null;
      }
    }

    public static Integer getInteger(Class<?> className,String type){
      Properties properties = new Properties();
      try {
        properties.load(className.getResourceAsStream("/commons-zhzhair.properties"));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      if("codeCount".equals(type)){
        return Integer.parseInt(properties.getProperty("codeCount"));
      }else if("width".equals(type)){
        return Integer.parseInt(properties.getProperty("width"));
      }else if("height".equals(type)){
        return Integer.parseInt(properties.getProperty("height"));
      }else if("grayIndex".equals(type)){
        return Integer.parseInt(properties.getProperty("grayIndex"));
      }else if("dotsNum".equals(type)){
        return Integer.parseInt(properties.getProperty("dotsNum"));
      }else if("dotsLen".equals(type)){
        return Integer.parseInt(properties.getProperty("dotsLen"));
      }else if("fontSize".equals(type)){
        return Integer.parseInt(properties.getProperty("fontSize"));
      }else if("wave".equals(type)){
        return Integer.parseInt(properties.getProperty("wave"));
      }else if("marginleft".equals(type)){
        return Integer.parseInt(properties.getProperty("marginleft"));
      }else if("paddingright".equals(type)){
        return Integer.parseInt(properties.getProperty("paddingright"));
      }else if("bottomtotop".equals(type)){
        return Integer.parseInt(properties.getProperty("bottomtotop"));
      }else{
        try {
          throw new Exception("the key does not exit");
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        return null;
      }
    }

    public static Double getDouble(Class<?> className,String type){
      Properties properties = new Properties();
    try {
      properties.load(className.getResourceAsStream("/commons-zhzhair.properties"));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if("codeRatio".equals(type)){
      return Double.parseDouble(properties.getProperty("codeRatio"));
    }else{
      try {
        throw new Exception("the key does not exit");
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return null;
    }
  }

   6.ImgCode.java实现验证码的方法

   private static final String STR = PropertiesValues.getString(ImgCode.class, "checkcodeStr");
   private static final String FACESTR = PropertiesValues.getString(ImgCode.class, "checkcodeFace");
   private static final int CODECOUNT = PropertiesValues.getInteger(ImgCode.class, "codeCount");
   private static final int WIDTH = PropertiesValues.getInteger(ImgCode.class, "width");
   private static final int HEIGHT = PropertiesValues.getInteger(ImgCode.class, "height");
   private static final int GRAYINDEX = PropertiesValues.getInteger(ImgCode.class, "grayIndex");
   private static final int FONTSIZE = PropertiesValues.getInteger(ImgCode.class, "fontSize");
   private static final int WAVE = PropertiesValues.getInteger(ImgCode.class, "wave");
   private static final int MARGINLEFT = PropertiesValues.getInteger(ImgCode.class, "marginleft");
   private static final int PADDINGRIGHT = PropertiesValues.getInteger(ImgCode.class, "paddingright");
   private static final int BOTTOMTOTOP = PropertiesValues.getInteger(ImgCode.class, "bottomtotop");
   private static final double CODERATIO = PropertiesValues.getDouble(ImgCode.class, "codeRatio");
   /**
    * @todo 生成不同颜色字符拼接的验证码字符串
    */
    public static String codeCreateWithColor(OutputStream outputStream){
      /*添加图片和画笔*/
      BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
      Graphics2D graphics2d = (Graphics2D) bufferedImage.getGraphics();
      graphics2d.setColor(new Color(GRAYINDEX,GRAYINDEX,GRAYINDEX));
      graphics2d.fillRect(0, 0, WIDTH, HEIGHT);
      /*选择加粗的数字,并拼接到一起*/
      StringBuffer sb = new StringBuffer();
      Set<Integer> set = getSet(CODECOUNT);//随机获取图片中的n/2~n-1个验证码
      for (int i = 0; i < CODECOUNT; i++) {
        if(set.contains(i)){
          graphics2d.setFont(new Font(FACESTR, Font.BOLD, (int)(FONTSIZE*CODERATIO)));
        }else{
          graphics2d.setFont(new Font(FACESTR, Font.PLAIN, FONTSIZE));
        }
        graphics2d.setColor(new Color(new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256)));
        String str = STR.charAt(new Random().nextInt(STR.length()))+"";
        graphics2d.drawString(str, MARGINLEFT+PADDINGRIGHT*i, BOTTOMTOTOP+new Random().nextInt(WAVE));
        if(set.contains(i)){
          sb.append(str);
        }
      }
      graphics2d.dispose();
      /*作为输出流输出*/
      try {
        ImageIO.write(bufferedImage, "JPEG" , outputStream);
      } catch (FileNotFoundException e) {e.printStackTrace();
      } catch (IOException e) {e.printStackTrace();}
      return sb.toString();
    }
    //随机获取图片中的n/2~n-1个验证码
    public static Set<Integer> getSet(Integer n){
      Set<Integer> set = new HashSet<Integer>();
      int countneed = n/2;
      int count = new Random().nextInt(countneed+1)+countneed;
      while(set.size()<count-1){
        set.add(new Random().nextInt(n));
      }
      return set;
    }

    7.UserController.java写验证码到html

    @RequestMapping(value = "http://www.mamicode.com/loginimg")
    public void showImgCode(HttpServletRequest req,

      /*取消浏览器缓存*/
      HttpServletResponse resp) {
      resp.setHeader("Pragma", "No-cache");
      resp.setHeader("Cache-Control", "No-cache");
      resp.setDateHeader("Expires", 0);


      try {
        req.getSession().setAttribute("imgCode", ImgCode.codeCreateWithColor(resp.getOutputStream()));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

验证码选择加粗的数字案例