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

设计目的

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

验证码效果图(访问地址: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="/"></property>
    <property name="suffix" value=".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="loginimg.do" onclick="this.src=‘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 = "/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();
      }
    }

时间: 2024-08-07 21:17:04

验证码选择加粗的数字案例的相关文章

latex数字加粗后变宽

latex的数字默认用的是Times New Roman字体,这个字体有个不优美之处就是加粗后会变宽,如下图所示: 平常倒是也无所谓.昨天在把实验数据整理进表格时,为了凸显每个数据集上各个实验方法的优劣,我把最好的方法的结果加粗显示,结果本来工工整整的表格就变的参差不齐了.后来查了不少资料,也只找到一个不甚漂亮的补救方法,就是在文章开头添上下面两句声明: \DeclareFixedFont{\myfont}{OT1}{ptm}{m}{n}{11pt} \DeclareFixedFont{\myf

CSS:字体样式(字体系列、大小、加粗、风格、变形等)

CSS 字体属性定义文本的(如斜体)和变形(如小型大写字母) 代码整理自w3school:http://www.w3school.com.cn <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <meta http-equiv=&q

LaTex中文字体加粗的问题

1. 字体加粗原理. 打开c/windows/fonts目录,以图标形式查看,我们可以发现有的图标是一张纸的样子,有的图标是几张纸叠着的样子.双击几张纸样子的图标,比如Arial,发现里面有很多个文件,有的文件名带黑体,说明对于Arial,字体文件单独区分了常规体和粗体. 我浏览了一下,发现英文大多数都单独定义了粗体,斜体,但是中文字体只有很少的会单独定义,只有雅黑和等线. 那么没有定义的字体,在加粗时,其实是软件做了简单地描边,效果肯定没有单独定义的好. 2. LaTex字体概念 LaTex字

css基础 给p标签中的内容 加粗,斜体,下划线,字体大小

镇场诗: 清心感悟智慧语,不着世间名与利.学水处下纳百川,舍尽贡高我慢意. 学有小成返哺根,愿铸一良心博客.诚心于此写经验,愿见文者得启发.------------------------------------------ part code: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8

能够设置文本加粗的样式属性

字体加粗(font-weight) 功能:用于设置字体笔划的粗细 属性值:正常度 -normal 相对度 -bold,bolder,light,lighter 渐变度 -100,200,300,400,500(相当于normal)600,700,800,900(相当于bold,lighter,bolder) 语法为:h1{font-weight:属性值}

&lt;strong&gt;加粗 and &lt;em&gt;斜体

<strong> 标签中的内容,通常是用加粗的字体(相对于斜体<em>)来显示其中的内容 源码: <body> <strong>徐志摩人物简介</strong> <p> <em>1910</em>年入杭州学堂<br/> <em>1918</em>年赴美国克拉大学学习银行学<br/> <em>1921</em>年开始创作新诗<br/&g

字体加粗

<b></b>.<strong></strong>标签都能实现字体的加粗(主要是对关键字进行加粗,目的是为了告诉搜索引擎这是我们页面所要表达的主题),但是它对优化是有影响的.所以建议使用<span></span>标签,即-------> span { font-weight:bold; }

【html】斜体、加粗、下划线

<head>     <meta charset="UTF-8"> </head> <body>     <h1>40.6摄氏度:上海创出140年气象史上高温新纪录</h1>     2013年07月27日 <br/>     10:58:26 来源:<b>新华网</b> <!-- <strong>新华网</strong> 加粗-->     

C# DataGrid根据某列的内容设置行字体加粗 单元格设置对齐方式

最近做了个功能,DataGrid显示具体内容的时候,根据某列分组. 每个分组具体内容后边,增加一行显示合计信息. 查询数据时,使用了union all将分组数据与明细数据合并起来,使用了排序达到了预期的效果. 绑定数据的时候,为了合计行比较醒目,所以把合并行加粗了,合计列居中. 界面如下图: DataGrid前台: 1 <asp:DataGrid ID="dgList" DataKeyField="ID" runat="server" Au