`
vincent_com
  • 浏览: 42020 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类

Java生成验证码

 
阅读更多
kaptcha
1.
kaptcha一个很好用的验证码插件,java版的,很不错的一个插件,只用简单的在web.xml中设置几个属性,一个很漂亮的验证码就出来了。其他的参数都可以自己设置,最牛的就是提供了接口,可以自己定义哦。
[代码] html代码
 
<form action="submit.action">
 
    <img src="kaptcha.jpg" /> <input type="text" name="kaptcha" value="" />
 
</form>
[代码] web.xml
 
<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>
[代码] java代码
 
String kaptchaExpected = (String)request.getSession()
 
    .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
 
String kaptchaReceived = request.getParameter("kaptcha");
 
 
 
if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected))
 
{
 
    setError("kaptcha", "Invalid validation code.");
 
}
[代码] 根据点击显示验证码
 
<img src="/kaptcha" width="200" id="kaptchaImage" />
 
<script type="text/javascript">
 
    $(function(){
 
        $('#kaptchaImage').click(function () {
 
            $(this).attr('src', '/kaptcha.jpg?' + Math.floor(Math.random()*100) );
 
        })
 
    });
 
</script>
 
<br /><small>Can't read the image? Click it to get a new one.</small>






jcaptcha
2.
前言:
现在很多系统和网站使用场景都使用验证码来增强系统安全性。
下面介绍jcaptcha来产生验证码和验证 http://jcaptcha.sourceforge.net/

下面的程序代码参考和仿照了springside3的实现
1.在web.xml上增加验证码的过滤器

创建验证码图形的Filter
    <filter-mapping>
        <filter-name>jcaptchaFilter</filter-name>
        <url-pattern>/jcaptcha.jpg</url-pattern>
    </filter-mapping>

验证的Filter
    <filter-mapping>
        <filter-name>jcaptchaFilter</filter-name>
        <url-pattern>/check</url-pattern>
    </filter-mapping>

自己写用jcaptcha产生验证码和验证实现的filter
    <filter>
        <filter-name>jcaptchaFilter</filter-name>
        <filter-class>security.jcaptcha.JCaptchaFilter</filter-class>
        <init-param><!--失败时的返回页面 -->
            <param-name>failureUrl</param-name>
            <param-value>/head.vm</param-value>
        </init-param>
    </filter>


2.获取验证码
在介绍图形码过滤器前,介绍一下jcaptcha产生验证码的api和code
验证码产生和验证需要jcaptcha的com.octo.captcha.service.image.DefaultManageableImageCaptchaService类的服务

产生验证码,并以图片信息输出到客户端
获取验证码的方法: captchaService.getChallengeForID(id)
根据你的id随机产生验证码

代码片段
protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
            throws IOException {

//设置response,输出图片客户端不缓存
response.setDateHeader("Expires", 1L);
response.addHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
response.setContentType("image/jpeg");

ServletOutputStream out = response.getOutputStream();

//获取验证码
  try {
            String captchaId = request.getSession(true).getId();
	      //用session的id来产生验证码
            BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale());//获取验证码
            ImageIO.write(challenge, "jpg", out);
            out.flush();
      } catch (CaptchaServiceException e) {
            System.out.println(e);
       } finally {
            out.close();
       }
}

在显示层,展示验证码<img id="captchaImg" src="显示验证码的过滤器url"/>


3.验证码验证
在介绍图形码过滤器前,介绍一下jcaptcha产生验证码的api和code
验证码产生和验证需要jcaptcha的com.octo.captcha.service.image.DefaultManageableImageCaptchaService类的服务

产生验证码,并以图片信息输出到客户端
获取验证码的方法: captchaService.validateResponseForID(captchaID, 输入的验证码);
返回值true 表示验证通关,false表示验证还没有通过

代码片段
    protected boolean validateCaptchaChallenge(final HttpServletRequest request) {
        try {
            //获取产生验证码的id,用session的id来产生验证码
            String captchaID = request.getSession().getId();
           //获取输入的验证码
            String challengeResponse = request.getParameter(captchaParamterName);
            return captchaService.validateResponseForID(captchaID, challengeResponse);
        } catch (CaptchaServiceException e) {
            System.out.println(e);
            return false;
        }
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics