用户登录验证码

为避免sql注入,用户登录时使用验证码:

<div class="formArea">
				<div class="formAreaTit">用户登录</div>
				<div class="userName">
					<input type="text" name="username" id="username" class="required">
				</div>
				<div class="password">
					<input type="password" name="password" id="password" class="required">
				</div>
				<div class="yanzhengma">
					<img src="${pageContext.request.contextPath}/login/validatePatchca?randomNum=1" title="看不清,点击图片更换验证码" id="validate"  width="80px" height="30px"/>
					<input type="text" placeholder="验证码" id="imgjudge">
				</div>
				<div class="loginBtn">
					<button οnclick="login()">登录</button>
				</div>
				<dd class="cytip" style="color:red; margin-top:8px;"></dd>
			</div>


用户登录验证:

<script type="text/javascript">
		$(document).ready(function(){			
	 		$('#validate').click(function(){
	 			//获取验证码
	 			$('#validate').attr("src", "${pageContext.request.contextPath}/login/validatePatchca?randomNum="+new Date().getTime());
	 		});
	 		$("#username").blur();
	 		$("#password").blur();
	 		$("#imgjudge").blur();
	 	}); 	
		
		function login(){
		//用户登录
			var loginName=$("#username").val();
  			var password=$("#password").val();
  			var img = $("#imgjudge").val();
  			
  			if(loginName==""||password==""){
				//$(".cytip").html("用户名或者密码不能为空");
				alert("用户名或者密码不能为空");
				return;
 			}
 			
 			if(!img){
  				//$(".cytip").html("请输入验证码");
  				alert("请输入验证码");
				return;
  			}
  						
  			var content = '';
  			$.ajax({
				type : "GET",
				async: false,
				url : "${pageContext.request.contextPath}/login/getSessionPatchca?r="+new Date().getTime(),
				success : function(data) {
					content = data;
				}
			});
  			if(img!=content){
  				//$(".cytip").html("验证码输入错误");
  				alert("验证码输入错误");
				return;
  			}
  			$(".cytip").html("");
  			
			$.ajax({
				type : "GET",
				async: false,
				url : "${pageContext.request.contextPath}/login/ajaxValidationUser?username="+loginName+"&password="+password,
				success : function(data) {
					if(data=="false"){
						//$(".cytip").html("用户名或者密码错误");
						alert("用户名或者密码错误");
						return;
					}
					$(".cytip").html("");
	  				window.location.href = "${pageContext.request.contextPath}/registrationSystem/article_pageList.action";	
				}
			});				
		}	
		//用户登录,异步将信息传到后台进行验证		
	</script>

动作类:LoginAction

public void validatePatchca(){
		ValidatePatchca.patchca(ServletActionContext.getRequest(), ServletActionContext.getResponse());	
	}
	public String token;

	public String getSessionPatchca() {
		token = (String)ServletActionContext.getRequest().getSession().getAttribute("PATCHCA");
		return "getSessionPatchca";
	}
	//通过密码和用户名进行验证
	public String ajaxValidationUser(){   
		//对password进行md5加密
		String passwordMD5 = new Md5PasswordEncoder().encodePassword(password, null);
		user = busi.getUserByNameAndPassword(username, passwordMD5);
		
		if(user!=null){			
			ActionContext.getContext().getSession().put("user", user);
			result="ture";
		}else{
			result="false";
		}
		return "ajaxValidationUser";
	}


//获取验证码的工具类

public class ValidatePatchca {
	private static void init(ConfigurableCaptchaService cs, final Random random){
		cs.setColorFactory(new ColorFactory() {
            @Override
            public Color getColor(int x) {
                int[] c = new int[3];
                int i = random.nextInt(c.length);
                for (int fi = 0; fi < c.length; fi++) {
                    if (fi == i) {
                        c[fi] = random.nextInt(71);
                    } else {
                        c[fi] = random.nextInt(256);
                    }
                }
                return new Color(c[0], c[1], c[2]);
            }
        });
        RandomWordFactory wf = new RandomWordFactory();
        wf.setCharacters("123456789");
        wf.setMaxLength(4);
        wf.setMinLength(4);
        cs.setWordFactory(wf);
	}
	
	public static void patchca(HttpServletRequest request, HttpServletResponse response){
		ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
		Random random = new Random();
		init(cs,random);
		try{
			switch (random.nextInt(5)) {
	            case 0:
	                cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
	                break;
	            case 1:
	                cs.setFilterFactory(new MarbleRippleFilterFactory());
	                break;
	            case 2:
	                cs.setFilterFactory(new DoubleRippleFilterFactory());
	                break;
	            case 3:
	                cs.setFilterFactory(new WobbleRippleFilterFactory());
	                break;
	            case 4:
	                cs.setFilterFactory(new DiffuseRippleFilterFactory());
	                break;
			}
	        HttpSession session = request.getSession(false);
	        if (session == null) {
	            session = request.getSession();
	        }
	        OutputStream os = response.getOutputStream();
	        response.reset();
	   	 	response.setContentType("image/png");
	        response.setHeader("Cache-Control", "no-cache, no-store");
	        response.setHeader("Pragma", "no-cache");
	        long time = System.currentTimeMillis();
	        response.setDateHeader("Last-Modified", time);
	        response.setDateHeader("Date", time);
	        response.setDateHeader("Expires", time);
	        response.flushBuffer();
	        String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", os);
	        session.setAttribute("PATCHCA", token);
	        os.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值