captcha实现验证码验证用户登录,防止密码被暴力破解。
下面是在Springmvc框架中运行。
导入的jar包:
kaptcha-2.3.2.jar
下载地址:http://download.csdn.net/detail/u013147600/9052871
或是在maven ---pom.xml:配置如下
<!-- 验证码工具 -->
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
Web.xml的配置
<span style="font-size:14px;"><!-- 验证码Servlet --> <servlet> <servlet-name>kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>kaptcha</servlet-name> <url-pattern>/kaptcha.jpg</url-pattern> </servlet-mapping></span>
springmvc.xml 配置
(captchaProducer相当于一个类,用户而已根据自己的要求对其属性进行修改)
<span style="font-size:14px;"> <!-- captcha一些属性的配置 --> <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <prop key="kaptcha.border">yes</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">blue</prop> <prop key="kaptcha.image.width">125</prop> <prop key="kaptcha.image.height">45</prop> <prop key="kaptcha.textproducer.font.size">45</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop> </props> </constructor-arg> </bean> </property> </bean></span>
SpringUtils.java 解析类
(用于解析springmvc.xml中的bean)
<span style="font-size:14px;">package com.authc.utils; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author lyx * * 2015-8-18下午3:53:19 * *com.utils.SpringUtil * TODO */ public class SpringUtil { private static ApplicationContext ctx =new ClassPathXmlApplicationContext("springmvc.xml"); public static Object getBean(String beanId) { return ctx.getBean(beanId); } } </span>
UserController控制层类
<span style="font-size:14px;">@Controller @RequestMapping("/member") public class UserController { private Producer captchaProducer; @RequestMapping(value = "captcha-image") public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); //获取springmvc.xml中的captchaProducer Bean captchaProducer = (Producer) SpringUtil.getBean("captchaProducer"); String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY); System.out.println("系统生成的验证码: " + code ); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String capText = captchaProducer.createText(); //将系统生成的验证码放入Session中 session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } return null; } @RequestMapping("/checkCode") public String checkCode(HttpServletRequest request) { //获取用户输入的验证码 String submitCode = WebUtils.getCleanParam(request,"j_code"); //从session中获取系统生成的验证码 String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); System.out.println("用户输入的验证码是:"+submitCode+",系统生成的验证码:"+kaptchaExpected); //进行比较 if(StringUtils.isEmpty(submitCode) || StringUtils.equalsIgnoreCase(submitCode, kaptchaExpected)) { request.setAttribute("checkCode","验证码正确!"); }else { request.setAttribute("checkCode","验证码错误!"); } return "/kaptcha"; } } </span>
注:这里是在Controller中进行验证,比较合适的方法应该是在js里面对用户输入的验证码进行验证
kaptcha.jsp页面
<span style="font-size:14px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page isELIgnored="false"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>验证码</title> <script type="text/javascript" src="<%=request.getContextPath()%>/res/js/jquery-1.11.3.min.js"> </script></head> <body> <script type="text/javascript"> $(function(){ //生成验证码 $('#kaptchaImage').click(function () { $(this).hide().attr('src', '<%=path%>/member/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); }); }); window.onbeforeunload = function(){ //关闭窗口时自动退出 if(event.clientX>360&&event.clientY<0||event.altKey){ alert(parent.document.location); } }; function changeCode() { //刷新 $('#kaptchaImage').hide().attr('src', '<%=path%>/member/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); event.cancelBubble=true; } </script> <div class="form-group"> <label>验证码 </label> <form action="<%=path%>/member/checkCode"> <input name="j_code" type="text" id="kaptcha" maxlength="4" class="form-control" /> <br/> <img src="<%=path%>/member/captcha-image" id="kaptchaImage" style="margin-bottom: -3px"/> <a href="#" onclick="changeCode()">看不清?换一张</a> <input type="submit" value="验证"> <span>${checkCode }</span> </form> </div> </body> </html> </span>
kaptcha可配置项:
kaptcha.border 是否有边框 默认为true 我们可以自己设置yes,no kaptcha.border.color 边框颜色 默认为Color.BLACK kaptcha.border.thickness 边框粗细度 默认为1 kaptcha.producer.impl 验证码生成器 默认为DefaultKaptcha kaptcha.textproducer.impl 验证码文本生成器 默认为DefaultTextCreator kaptcha.textproducer.char.string 验证码文本字符内容范围 默认为abcde2345678gfynmnpwx kaptcha.textproducer.char.length 验证码文本字符长度 默认为5 kaptcha.textproducer.font.names 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) kaptcha.textproducer.font.size 验证码文本字符大小 默认为40 kaptcha.textproducer.font.color 验证码文本字符颜色 默认为Color.BLACK kaptcha.textproducer.char.space 验证码文本字符间距 默认为2 kaptcha.noise.impl 验证码噪点生成对象 默认为DefaultNoise kaptcha.noise.color 验证码噪点颜色 默认为Color.BLACK kaptcha.obscurificator.impl 验证码样式引擎 默认为WaterRipple kaptcha.word.impl 验证码文本字符渲染 默认为DefaultWordRenderer kaptcha.background.impl 验证码背景生成器 默认为DefaultBackground kaptcha.background.clear.from 验证码背景颜色渐进 默认为Color.LIGHT_GRAY kaptcha.background.clear.to 验证码背景颜色渐进 默认为Color.WHITE kaptcha.image.width 验证码图片宽度 默认为200 kaptcha.image.height 验证码图片高度 默认为50
简单的效果图:
参考:http://blog.csdn.net/rambo_china/article/details/7720181
http://cuisuqiang.iteye.com/blog/2048428
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 19:01:55