Spring之验证码的生成与校验

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

 

主要流程:

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

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

3、  输出到页面

 

Controller中:

    /**
     * 生成验证码
     * @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 < 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 < 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();
    }

页面部分:

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../js/jquery.form_utf8.js"></script>
<link rel="stylesheet" href="../css/rabb.css">
<title>Insert title here</title>
</head>
<body>
	<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>
	</div>
	<div class="more">
		<div class="menudiv"><a href="javascript:;" id="btn">登录</a><a href="javascript:;" id="btn2">退出</a></div>
	</div>
</body>

<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>
</html>

实现效果:

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

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值