struts2 实现图片验证码 jsp annocation

Step 1.随机验证码

  一步一步来,要生成验证码图片,首先要有验证码,然后才能在画在图片上。为了能够灵活控制验证码,特别编写了SecurityCode类,它向外提供随机字符串。并且可以控制字符串的长度和难度。SecurityCode类中提供的验证码分三个难度,易(全数字)、中(数字+小写英文)、难(数字+大小写英文)。难度使用枚举SecurityCodeLevle表示,避免使用1、2、3这样没有明确意义的数字来区分。

  同时,还控制了能否出现重复的字符。为了能够方便使用,方法设计为static。

  SecurityCode类:

importjava.util.Arrays;

 

publicclass SecurityCode {

 

   

   public enum SecurityCodeLevel{

      Simple, Medium,Hard

   };

 

   

   public static String getSecurityCode() {

      return getSecurityCode(4,SecurityCodeLevel.Medium,false);

   }

 

   

   public static String getSecurityCode(int length, SecurityCodeLevellevel,

          boolean isCanRepeat) {

      // 随机抽取len个字符

      int len = length;

      // 字符集合(除去易混淆的数字0、数字1、字母l、字母o、字母O)

      char[] codes = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',

             'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p',

             'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',

             'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',

             'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

      // 根据不同的难度截取字符数组

      if (level == SecurityCodeLevel.Simple) {

          codes = Arrays.copyOfRange(codes, 0, 9);

      } else if (level ==SecurityCodeLevel.Medium) {

          codes = Arrays.copyOfRange(codes, 0, 33);

      }

      // 字符集合长度

      int n = codes.length;

      // 抛出运行时异常

      if (len > n && isCanRepeat ==false) {

         throw new RuntimeException(String.format("调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常,当isCanRepeat为%3$s时,传入参数%1$s不能大于%4$s", len, level, isCanRepeat, n));

      }

 

      // 存放抽取出来的字符

      char[] result =new char[len];

 

      // 判断能否出现重复的字符

      if (isCanRepeat) {

          for (inti = 0; i < result.length; i++) {

             // 索引 0 and n-1

             int r = (int) (Math.random() * n);

 

             // 将result中的第i个元素设置为codes[r]存放的数值

             result[i] = codes[r];

          }

      } else {

          for (inti = 0; i < result.length; i++) {

             // 索引 0 and n-1

             int r = (int) (Math.random() * n);

 

             // 将result中的第i个元素设置为codes[r]存放的数值

             result[i] = codes[r];

 

             // 必须确保不会再次抽取到那个字符,因为所有抽取的字符必须不相同。

             // 因此,这里用数组中的最后一个字符改写codes[r],并将n减1

             codes[r] = codes[n - 1];

             n--;

          }

      }

      return String.valueOf(result);

   }

}

Step 2.图片

     第一步已经完成,有了上面SecurityCode类提供的验证码,就应该考虑怎么在图片上写字符串了。在Java中操作图片,需要使用BufferedImage类,它代表内存中的图片。写字符串,就需要从图片BufferedImage上得到绘图图面Graphics,然后在图面上drawString。

    为了使验证码有一定的干扰性,也绘制了一些噪点。调用Graphics类的drawRect绘制1*1大小的方块就可以了。

    特别说明一下,由于后面要与Strtus2结合使用,而在Struts2中向前台返回图片数据使用的是数据流的形式。所以提供了从图片向流的转换方法convertImageToStream。

     SecurityImage类:

importjava.awt.Color;

importjava.awt.Font;

importjava.awt.Graphics;

importjava.awt.image.BufferedImage;

importjava.io.ByteArrayInputStream;

importjava.io.ByteArrayOutputStream;

importjava.io.IOException;

importjava.util.Random;

importcom.sun.image.codec.jpeg.ImageFormatException;

importcom.sun.image.codec.jpeg.JPEGCodec;

importcom.sun.image.codec.jpeg.JPEGImageEncoder;

 

publicclass SecurityImage {

 

   

   public static BufferedImage createImage(String securityCode) {

 

      // 验证码长度

      int codeLength = securityCode.length();

      // 字体大小

      int fSize = 15;

      int fWidth = fSize + 1;

      // 图片宽度

      int width = codeLength * fWidth + 6;

      // 图片高度

      int height = fSize * 2 + 1;

 

      // 图片

      BufferedImage image = new BufferedImage(width,height,

             BufferedImage.TYPE_INT_RGB);

      Graphics g = image.createGraphics();

 

      // 设置背景色

      g.setColor(Color.WHITE);

      // 填充背景

      g.fillRect(0, 0, width, height);

 

      // 设置边框颜色

      g.setColor(Color.LIGHT_GRAY);

      // 边框字体样式

      g.setFont(newFont("Arial",Font.BOLD, height - 2));

      // 绘制边框

      g.drawRect(0, 0, width - 1, height - 1);

 

      // 绘制噪点

      Random rand = new Random();

      // 设置噪点颜色

      g.setColor(Color.LIGHT_GRAY);

      for (inti = 0; i < codeLength * 6; i++) {

          int x = rand.nextInt(width);

          int y = rand.nextInt(height);

          // 绘制1*1大小的矩形

          g.drawRect(x, y, 1, 1);

      }

 

      // 绘制验证码

      int codeY = height - 10;

      // 设置字体颜色和样式

      g.setColor(newColor(19, 148, 246));

      g.setFont(newFont("Georgia",Font.BOLD, fSize));

      for (inti = 0; i < codeLength; i++) {

          g.drawString(String.valueOf(securityCode.charAt(i)), i * 16+ 5,

                 codeY);

      }

      // 关闭资源

      g.dispose();

 

      return image;

   }

 

   

   public static ByteArrayInputStream getImageAsInputStream(StringsecurityCode) {

 

      BufferedImage image = createImage(securityCode);

      return convertImageToStream(image);

   }

 

   

   private static ByteArrayInputStream convertImageToStream(BufferedImageimage) {

 

      ByteArrayInputStream inputStream =null;

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      JPEGImageEncoder jpeg =JPEGCodec.createJPEGEncoder(bos);

      try {

          jpeg.encode(image);

          byte[] bts = bos.toByteArray();

          inputStream =new ByteArrayInputStream(bts);

      } catch (ImageFormatException e) {

          e.printStackTrace();

      } catch (IOException e) {

          e.printStackTrace();

      }

      return inputStream;

   }

}

Step 3.验证码与Struts 2结合

  这里采用的是action注解的方式来配置。

 private String verifycode;
    private ByteArrayInputStream  imageStream;

    /**
     *
     * @Title: register
     * @Description: 注册时输入验证码
     * @param @return
     * @return String
     * @throws
     */

        @Action(value = "/ValidCode", interceptorRefs = @InterceptorRef("defaultStack"), results = {
            @Result(name = "success", type = "stream",
                    params = {"contentType", "image/jpeg","inputName", "imageStream", "bufferSize", "4096" })
            })

    public String validCode(){

             //如果开启Hard模式,可以不区分大小写  
            //String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();  
              
            //获取默认难度和长度的验证码  
            String securityCode = SecurityCode.getSecurityCode();  
            System.out.println("securityCode=="+securityCode);
            imageStream = SecurityImage.getImageAsInputStream(securityCode);  
            //放入session中  
            ActionContext.getContext().getSession().put("securityCode", securityCode);  

        return SUCCESS;
    }
/**
         * 判断用户输入验证码是否正确
         *
         * @return
         */
        @Action(value = "/user/verifycode", interceptorRefs = @InterceptorRef("defaultStack"), results = { @Result(name =

SUCCESS, type = "json") })
        public String verify() {
            System.out.println("verifycode==" + verifycode);
            String securityCode=(String)ActionContext.getContext().getSession().get("securityCode");
            System.out.println("securityCode==" + securityCode);
            if (!securityCode.equals(verifycode)) {
                errorname = "codewrong";
            }
            return SUCCESS;
        }


    public ByteArrayInputStream getImageStream() {
        return imageStream;
    }

    public void setImageStream(ByteArrayInputStream imageStream) {
        this.imageStream = imageStream;
    }
    @JSON(serialize = false)
    public String getVerifycode() {
        return verifycode;
    }

    public void setVerifycode(String verifycode) {
        this.verifycode = verifycode;
    }

如果你采用的是struts.xml配置文件,

<!-- Random验证码 -->
<action name="ValidCode" class="ValidCode">
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
</result>
</action>

 3)前台JSP

  定义一个img元素,将src指向ValidCode.action就可以了,浏览器向Action发送请求,服务器将图片流返回,图片就能够显示了。

<!-- 验证码 -->
 <input type="text" id="verifycode" name="verifycode" οnblur="verify()"/>
  <img src="ValidCode.action" id="Verify"  style="cursor:pointer;" alt="看不清,换一张"/>
 <!-- 验证码 end-->

  4)JS

     验证码一般都有点击刷新的功能,这个也容易实现,点击图片,重新给图片的src赋值。但是这时,浏览器会有缓存问题,如果浏览器发现src中的url不变,就认为图片没有改变,就会使用缓存中的图片,而不是重新向服务器请求。解决办法是在url后面加上一个时间戳,每次点击时,时间戳都不一样,浏览器就认为是新的图片,然后就发送请求了。在這里我加了一個驗證碼是否正確的功能。

    jQuery:

复制代码
//点击图片更换验证码 
$(function () {  
      //点击图片更换验证码
    $("#Verify").click(function(){
            $(this).attr("src","ValidCode.action?timestamp="+new Date().getTime());
        });
     });
     
/*验证用户用户输入验证码是否正确  */
function verify() {
    var verifycode = $("#verifycode").val();
    $("#sp").html("");
    $.ajax({
        type : "POST",
        url : 'user/verifycode.action',
        data : {
            "verifycode" : verifycode
        },
        dataType : "json",
        success : function(msg) {
            var error = msg.errorname;
            if (error == 'codewrong'){
                $("#sp").html("验证码错误");
            }
                
        },
    });
}
复制代码

复制代码

 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值