生成验证码及使用

生成验证码的Servlet

public class ImageCodeServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        //req.setCharacterEncoding("utf-8");
        //res.setContentType("text/html;charset=utf-8");
        // 设置http响应的文件MIME类型为图片
        res.setContentType("image/jpeg");
        // 不让浏览器记录此图片的缓存
        res.setDateHeader("expries", -1);
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Pragma", "no-cache");
        // 这里调用了一个工具类VerifyCodeUtils来生成指定位数(也可指定内容)的验证码字符串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(5);
        // 将生成验证码字符串保存到session域中,方面进行表单验证
        req.getSession().setAttribute("verifyCode", verifyCode);
        // 生成图片并写到响应输出流里. 因为register.jsp页面里的验证码图片宽高分别为180,30.这里使保持一致
        VerifyCodeUtils.outputImage(180, 30, res.getOutputStream(), verifyCode);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGet(req, res);
    }
}

注册页面的使用

<script type="text/javascript">
	function changeImage() {		
		document.getElementById("img").src = "ImageCodeServlet?time="
				+ new Date().getTime();
	}
	
	function validate(){
			var code=$("#ckcode").val();
	    	if(code==null||code==""){    		
	    		$("#codeDiv").html("<font style='color:red'>验证码不能为空</font>");

	    	}else{    		
	    		$.getJSON('register',{code:code},function d(data){
					$("#codeDiv").html(data.msg);
				});	
	    	}
	}
	   
</script>
	<!-- 验证码 -->
    		<div class="checkimg">
    		<h4>注册校验</h4><br>
			<table width="100%" border="0" cellspacing="1" class="upline">
							<tr>
								<td style="text-align: left; width: 40%">输入校验码:</td>
								<td style="width: 60%"><input type="text" style="border:1px solid black; height:25px"
									name="ckcode" id="ckcode" onblur="validate()" /></td>
								
							</tr>
							<tr>
								<td style="text-align: right; width: 20%;"> </td>
								<td colspan="2" style="width: 90%"><img
									src="ImageCodeServlet" width="180"
									height="30"  id="img" />  
									<a href="javascript:void(0);" onclick="changeImage()">换一张</a>
								</td>
							</tr>
							<tr><td><span id="codeDiv"></span></td></tr>
						</table>
			</div>   			

JSON传给RegisterServlet,从session中取出验证码与输入的参数进行比较

String code=request.getParameter("code");
String c=(String) request.getSession().getAttribute("verifyCode");
if(c.equals(code)) {
	out.print("{\"flag\":\"true\",\"msg\":\"<font style='color:green'>验证码正确</font>\"}");
}else {
	out.print("{\"flag\":\"false\",\"msg\":\"<font style='color:red'>验证码错误</font>\"}");
}

猜你喜欢

转载自blog.csdn.net/weixin_36328444/article/details/80453010