码迷,mamicode.com
首页 > 其他好文 > 详细

验证码

时间:2014-07-10 20:02:42      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:验证码

<pre name="code" class="html"><p>
							<span id="sure-word" class="fond">验证码:</span>
								<span style="width:70px">
								<input id="Verification" name="Verification" type="text"
									size="6" style="width:60px"/>
								</span>
								<span id="vcodeValidMsg"></span>
								<span style="margin-left:10px;">
								<img src="EC/SecurityCodeImage" id="Verify" style="cursor: hand;" alt="看不清,换一张" /> 
								</span>
							</p>
							<span id="Verification.info" style="color:red"></span>



<pre name="code" class="javascript">//除掉字符串两端的空格
	function strip(str) {
		var reg = /(^\s*)|(\s*$)/g;
		return str.replace(reg, '');
	}
	function verfy_verfy11() {
		//flag.code = false;//设置成为通过检测
		var code = strip(document.getElementById("Verification").value);
		//非空检测
		if (code == "") {
			$("#Verification\\.info").html(
					"<img src='EC/user/images/wrong.gif'/>验证码不能为空!");
			return;
		}
		//ajax检测
		$("#Verification\\.info").html(
				//"<img src='../images/window_loading.gif'/>正在检测...");
		$.post("EC/user/valid.action", {
			"code" : code
		}, function(data) {
			if (data) {
				$("#Verification\\.info").html(
						"<img src='EC/user/images/right.gif'/>验证码正确!");
				flag.code = true;
			} else {
				$("#Verification\\.info").html(
						"<img src='EC/user/images/wrong.gif'/>验证码错误!");
			}
		}));
	}

<script>$(function() {//点击图片更换验证码$("#Verify").click(function() {$(this).attr("src","EC/SecurityCodeImage?timestamp="+ new Date().getTime());});});window.onload = function() {var verifyObj = document.getElementById("Verify");verifyObj.onclick = function() {this.src = "EC/SecurityCodeImage?timestamp="+ new Date().getTime();};};
	
</script>


$(document).ready(function() {
	
       //验证码检测
     	$(function() {
     		$("#Verification").blur(function() {
     			verfy_verfy11();
     		});
     	});
	});
      <pre name="code" class="html"> <package name="User" extends="struts-default" namespace="/EC">
	<!-- 验证码 -->
		<action name="SecurityCodeImage" class="biz.cld.web.action.user.SecurityCodeImageAction">
			<result name="success" type="stream">
				<param name="contentType">image/jpeg</param>
				<param name="inputName">imageStream</param>
				<param name="bufferSize">2048</param>
			</result>
		</action>
    </package>


<!--  ajax verfy-->
	<package name="userJson" extends="json-default" namespace="/EC">
		<!-- registerNameVerfy ajax-->
		<action name="registerNameVerfy"  class="userManageAction"  method="registerNameVerfy">
		   <result name="success" type="json">
		     <param name="root">verfy</param>
		   </result>
		   <result name="error" type="json">
		     <param name="root">verfy</param>
		   </result>
		</action>
		
		<!-- registerEmailVerfy ajax-->
		<action name="registerEmailVerfy" class="userManageAction"  method="registerEmailVerfy">
		   <result name="success">
		     <param name="root">verfy</param>
		   </result>
		   <result name="error" type="">
		     <param name="root">verfy</param>
		   </result>
		</action>
		
		<!-- ajax校验验证码 -->
		<action name="valid" class="biz.cld.web.action.user.ValidAction">
			<result name="success" type="json">
				<param name="root">ok</param>
			</result>
		</action>
		
		
	</package>

package biz.cld.web.action.user;
 
 import java.util.Arrays;
 
 /**
  * 工具类,生成随机验证码字符串
  * @version 1.0 2012/08/21
  * @author <span style="font-family: Arial, Helvetica, sans-serif;">曾修建</span>
  *
  */
 public class SecurityCode {
     
     /**
      * 验证码难度级别,Simple只包含数字,Medium包含数字和小写英文,Hard包含数字和大小写英文
      */
     public enum SecurityCodeLevel {Simple,Medium,Hard};
     
     /**
      * 产生默认验证码,4位中等难度
      * @return  String 验证码
      */
     public static String getSecurityCode(){
         return getSecurityCode(6,SecurityCodeLevel.Medium,false);
     }
     
     /**
      * 产生长度和难度任意的验证码
      * @param length  长度
      * @param level   难度级别
      * @param isCanRepeat  是否能够出现重复的字符,如果为true,则可能出现 5578这样包含两个5,如果为false,则不可能出现这种情况
      * @return  String 验证码
      */
     public static String getSecurityCode(int length,SecurityCodeLevel level,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);
         }
         else if(level==SecurityCodeLevel.Hard){
             codes=Arrays.copyOfRange(codes, 0,57);
         }
         
         //字符集合长度
         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(int i=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(int i=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);
     }
 }

package biz.cld.web.action.user;
 
 import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
 import java.io.ByteArrayInputStream;
 import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
 
 /**
  * 提供图片验证码
  * @version 1.0 2012/08/22
  * @author <span style="font-family: Arial, Helvetica, sans-serif;">曾修建</span>

  */
 @SuppressWarnings("serial")
 public class SecurityCodeImageAction extends ActionSupport implements SessionAware{
     
     //Struts2中Map类型的session
     private Map<String, Object> session;
     
     //图片流
     private ByteArrayInputStream imageStream;
 
     public ByteArrayInputStream getImageStream() {
         return imageStream;
     }
 
     public void setImageStream(ByteArrayInputStream imageStream) {
         this.imageStream = imageStream;
     }
 
     
     public String execute() throws Exception {
         //如果开启Hard模式,可以不区分大小写
 //        String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();
         
         //获取默认难度和长度的验证码
         String securityCode = SecurityCode.getSecurityCode();
         imageStream = SecurityImage.getImageAsInputStream(securityCode);
         //放入session中
     //   session.put("SESSION_SECURITY_CODE", securityCode);
         ActionContext.getContext().getSession().put("SESSION_SECURITY_CODE", securityCode);
         return SUCCESS;
     }
 
     public void setSession(Map<String, Object> session) {
         this.session = session;
     }
 
 }

package biz.cld.web.action.user;
 
 import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
 import java.io.ByteArrayInputStream;
 import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
 
 /**
  * 提供图片验证码
  * @version 1.0 2012/08/22
  * @author <span style="font-family: Arial, Helvetica, sans-serif;">曾修建</span>
  */
 @SuppressWarnings("serial")
 public class SecurityCodeImageAction extends ActionSupport implements SessionAware{
     
     //Struts2中Map类型的session
     private Map<String, Object> session;
     
     //图片流
     private ByteArrayInputStream imageStream;
 
     public ByteArrayInputStream getImageStream() {
         return imageStream;
     }
 
     public void setImageStream(ByteArrayInputStream imageStream) {
         this.imageStream = imageStream;
     }
 
     
     public String execute() throws Exception {
         //如果开启Hard模式,可以不区分大小写
 //        String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();
         
         //获取默认难度和长度的验证码
         String securityCode = SecurityCode.getSecurityCode();
         imageStream = SecurityImage.getImageAsInputStream(securityCode);
         //放入session中
     //   session.put("SESSION_SECURITY_CODE", securityCode);
         ActionContext.getContext().getSession().put("SESSION_SECURITY_CODE", securityCode);
         return SUCCESS;
     }
 
     public void setSession(Map<String, Object> session) {
         this.session = session;
     }
 
 }

package biz.cld.web.action.user;

import com.opensymphony.xwork2.ActionContext;

import biz.cld.framework.action.BaseActionImpl;

/**
 * 类说明
 *
 * @author 曾修建
 * @version 创建时间:2014-7-8 下午11:58:33
 */
public class ValidAction extends BaseActionImpl {
	private String code;//input
	private boolean ok=false;//output-->json
	public String execute()throws Exception{
		Thread.sleep(1000);
		//比较
		String scode=(String) ActionContext.getContext().getSession().get("SESSION_SECURITY_CODE");
		if(code.equalsIgnoreCase(scode)){
			ok=true;
		}else{
			ok=false;
		}
		return "success";//调用jsonResult输出ok
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public boolean isOk() {
		return ok;
	}
	public void setOk(boolean ok) {
		this.ok = ok;
	}
}



验证码,布布扣,bubuko.com

验证码

标签:验证码

原文地址:http://blog.csdn.net/wintersweetzeng/article/details/37591471

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!