lazzyRabbit hello

最近改了一下项目中的验证码部分,简单整理成了一个Demo。

主要流程:

1、  生成随机的验证码并放到session中

2、  生成图片(设置图片样式,写入验证码以及干扰内容)

3、  输出到页面

Controller中:

<code><code>    /**
     * 生成验证码
     * @throws IOException 
     */
    @RequestMapping("/maskCode")
    public void maskCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 产生4位随机数字
        Random random = new Random();
        String sRand = "";
        for (int i = 0; i &lt; 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
        }
        // 设定字体
        String fontPath = request.getSession().getServletContext().getRealPath("/fonts");
        PJAGraphicsManager graphicsManager;
        graphicsManager = PJAGraphicsManager.getDefaultGraphicsManager();
        graphicsManager.loadFonts(fontPath);

        // 画图
        Image localImage = new PJAImage(46, 20);
        Object localObject = localImage.getGraphics();
        ((PJAGraphicsExtension) localObject).setFont("", 1, 14);
        ((Graphics) localObject).setColor(Color.gray);
        ((Graphics) localObject).draw3DRect(0, 0, 45, 19, false);
        ((Graphics) localObject).setColor(Color.black);
        ((Graphics) localObject).drawString(sRand, 5, 16);
        Random localRandom = new Random(System.currentTimeMillis());
        for (int i = 0; i &lt; 80; ++i) {
            int j = localRandom.nextInt(46);
            int k = localRandom.nextInt(20);
            ((Graphics) localObject).drawLine(j, k, j, k);
        }
        sendGIFImage(localImage, response);
        //将验证码存入session
        request.getSession().setAttribute("maskCode", sRand);
    }
    /**
     * 将图片输出到浏览器
     * @param paramImage
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void sendGIFImage(Image paramImage, HttpServletResponse response)
            throws ServletException, IOException {
        // 禁止图像缓存。
        response.setContentType("image/gif");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        ServletOutputStream localServletOutputStream = response.getOutputStream();
        try {
            new GifEncoder(paramImage, localServletOutputStream).encode();
        } catch (IOException localIOException) {
            new GifEncoder(new FilteredImageSource(paramImage.getSource(),new Web216ColorsFilter()), localServletOutputStream).encode();
        }
        localServletOutputStream.flush();
    }</code></code>

页面部分:

<code><code>&nbsp;&nbsp;  <div id="mask">
	</div>
	<div id="login">
		<span id="close_login">×</span>
		<form name="loginForm" id="loginForm" action="../login/checkLogin">
		<ul>
			<li class="tit">登录</li>
			<li style="margin-top:40px;"><input name="username" id="username" type="text" placeholder="请输入用户名" class="input_username">
			</li>
			<li><input name="password" id="password" type="password" placeholder="请输入密码" class="input_password">
			</li>
			<li><input name="code" id="code" type="text" placeholder="请输入验证码" class="input_code">
			<img id="licenceImg" src="../login/maskCode" border="0" width="80px" height="30px" align="absmiddle" alt="验证码,看不清楚? 请点击刷新验证码" onclick="refreshImage();" style="cursor: pointer;">
			<a href="javascript:refreshImage();" style="font-size: 12px;color:#FF7F50;margin-left: 2px;">换一张</a>
			</li>
			<li style="margin-top:40px;"><input onclick="showRequest();" type="submit" class="input_submmit" onvalue="登录">
			</li>
			<li><span id="loginInfo" style="font-size: 14px;color:#FF7F50;margin-left: 2px;"></span></li>
		</ul>
	</form></div>
	<div class="more">
		<div class="menudiv"><a href="javascript:;" id="btn">登录</a><a href="javascript:;" id="btn2">退出</a></div>
	</div>

<script type="text/javascript">
$(document).ready(function() {
	var options = {
		beforeSubmit : showRequest, // pre-submit callback 
		success : showResponse, // post-submit callback 
		dataType : 'xml',
		resetForm : false
	};
	$('#loginForm').ajaxForm(options);
	var user = "${username}";
	if(user!=''){
		$("#btn").html("当前用户:"+user);
		$("#btn2").show();
		$("#btn2").click(function(){
			$("#mask").show();
			$("#login").show();
			window.location.href = "../login/logout";
		});
	}else{
		$("#btn").click(function(){
			$("#mask").show();
			$("#login").show();
			$("#loginInfo").html("");
		});
		$("#close_login").click(function(){
			$("#mask").hide();
			$("#login").hide();
		});
	}
});

function showRequest() {
	if($("#username").val()==""){
		$("#loginInfo").html("请输入用户名!");
		return false;
	}else if($("#password").val()==""){
		$("#loginInfo").html("请输入密码!");
		return false;
	}else if($("#code").val()==""){
		$("#loginInfo").html("请输入验证码!");
		return false;
	}else{
		$("#loginInfo").html("正在登陆...");
		return true;
	}
	
}
function showResponse(responseXML){
	var result = $("result", responseXML).text();
	var status = $("status", responseXML).text();
	$("#loginInfo").html(result);
	if(status==6){
		window.location.href = "../hellorabbit/login";
	}
}
function refreshImage(img) {
	var imageUrl = '../login/maskCode'; //生成图片
	var imgs = document.getElementById("licenceImg");
	imgs.src = imageUrl + '?' + Math.random();
}
</script>
</code></code>

实现效果:


Demo:http://download.csdn.net/download/lazyrabbitlll/10106020