Cage验证码生成器快速上手

Cage小巧,好用。这里在官方基础例子基础上做了扩展:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.lavasoft.ntv.web.common;
import com.github.cage.IGenerator;
import java.util.Random;
/**
 * 验证码生成器
 *
 * @author leizhimin 14-5-5 下午2:42
 */
public class MyTokenGenerator implements IGenerator<String> {
    private int length = 4;
    private String charsetdir = "23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ";
    private static final Random r = new Random();
    public MyTokenGenerator() {
    }
    public MyTokenGenerator(int length, String charsetdir) {
        this.length = length;
        this.charsetdir = charsetdir;
    }
    @Override
    public String next() {
        StringBuffer sb = new StringBuffer();
        int len = charsetdir.length();
        for (int i = 0; i < length; i++) {
            sb.append(charsetdir.charAt(r.nextInt(len - 1)));
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        MyTokenGenerator t = new MyTokenGenerator();
        for (int i = 0; i < 100; i++) {
            System.out.println(t.next());
        }
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.lavasoft.ntv.web.servlet;
import com.github.cage.Cage;
import com.lavasoft.ntv.web.common.MyTokenGenerator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 1490947492185481844L;
    private static final Cage cage = new Cage(null,null,null,null,nullnew MyTokenGenerator(),null);
    /**
     * Generates a captcha token and stores it in the session.
     *
     * @param session where to store the captcha.
     */
    public static void generateToken(HttpSession session) {
        String token = cage.getTokenGenerator().next();
        session.setAttribute("captchaToken", token);
        markTokenUsed(session, false);
    }
    /**
     * Used to retrieve previously stored captcha token from session.
     *
     * @param session where the token is possibly stored.
     * @return token or null if there was none
     */
    public static String getToken(HttpSession session) {
        Object val = session.getAttribute("captchaToken");
        return val != null ? val.toString() : null;
    }
    /**
     * Marks token as used/unused for image generation.
     *
     * @param session where the token usage flag is possibly stored.
     * @param used    false if the token is not yet used for image generation
     */
    protected static void markTokenUsed(HttpSession session, boolean used) {
        session.setAttribute("captchaTokenUsed", used);
    }
    /**
     * Checks if the token was used/unused for image generation.
     *
     * @param session where the token usage flag is possibly stored.
     * @return true if the token was marked as unused in the session
     */
    protected static boolean isTokenUsed(HttpSession session) {
        return !Boolean.FALSE.equals(session.getAttribute("captchaTokenUsed"));
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        String token = session != null ? getToken(session) : null;
        if (token == null || isTokenUsed(session)) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND,"Captcha not found.");
            return;
        }
        setResponseHeaders(resp);
        markTokenUsed(session, true);
        cage.draw(token, resp.getOutputStream());
    }
    /**
     * Helper method, disables HTTP caching.
     *
     * @param resp response object to be modified
     */
    protected void setResponseHeaders(HttpServletResponse resp) {
        resp.setContentType("image/" + cage.getFormat());
        resp.setHeader("Cache-Control""no-cache, no-store");
        resp.setHeader("Pragma""no-cache");
        long time = System.currentTimeMillis();
        resp.setDateHeader("Last-Modified", time);
        resp.setDateHeader("Date", time);
        resp.setDateHeader("Expires", time);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%--
  Created by IntelliJ IDEA.
  User: leizhimin 14-5-5 下午12:18
--%>
<%@page import="com.lavasoft.ntv.web.servlet.CaptchaServlet"%><%@
        page contentType="text/html" pageEncoding="UTF-8"%><%
    boolean showGoodResult;
    boolean showBadResult;
    if ("POST".equals(request.getMethod())) {
        String sessionToken = CaptchaServlet.getToken(session);
        String requestToken = request.getParameter("captcha");
        showGoodResult = sessionToken != null && sessionToken.equals(requestToken);
        showBadResult = !showGoodResult;
    } else {
        showGoodResult = showBadResult = false;
    }
    CaptchaServlet.generateToken(session);
%><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8" />
    <title>Captcha Reader</title>
</head>
<body>
<%  if (showGoodResult) {%>
<h1 style="color: green;">Your kung fu is good!</h1>
<%  } else if (showBadResult) {%>
<h1 style="color: red;">This is not right. Try again!</h1>
<%  } %>
<p>Type in the word seen on the picture</p>
<form action="" method="post">
    <input name="captcha" type="text" autocomplete="off" />
    <input type="submit" />
</form>
<img alt="captcha image" src="/ntv/captcha" width="120px" height="30px"/>
</body>
</html>


1
2
3
4
5
6
7
8
<servlet>
    <servlet-name>captcha</servlet-name>
    <servlet-class>com.lavasoft.ntv.web.servlet.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>captcha</servlet-name>
    <url-pattern>/captcha</url-pattern>
</servlet-mapping>


访问页面:


wKioL1NnS2_T5q1RAADnNYpJ3h4765.jpg




本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/1406702,如需转载请自行联系原作者


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/279406.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何更改您的iPhone铃声

The problem with having a popular phone like an iPhone is that, by default, everyone has the same ringtone. If you want to give your iPhone a more personal sound, here’s how to do it. 拥有像iPhone这样的流行手机的问题是&#xff0c;默认情况下&#xff0c;每个…

扒一扒那些年我们遇到的奇葩代码

前言 本文首发于公众号【一名打字员】 在工作中&#xff0c;我们通常会遇到传说中的“祖传”代码&#xff0c;有些是否让我们感到哭笑不得&#xff0c;今天本猿整理一下自己以及网络上出现过的奇葩代码。来源于互联网的均会标明出处。 TOP1 当仁不让的当然是传说中的“睡排序”…

相对湿度与绝对湿度_如何监视家里的湿度水平

相对湿度与绝对湿度High humidity is no fun, and neither is low humidity—you want a good balance between the two. Here’s how to monitor the humidity in your house so that you can make the proper adjustments. 高湿度无济于事&#xff0c;低湿度也无济于事-您希望…

基于redis实现的扣减库存

2019独角兽企业重金招聘Python工程师标准>>> 在日常开发中有很多地方都有类似扣减库存的操作&#xff0c;比如电商系统中的商品库存&#xff0c;抽奖系统中的奖品库存等。 解决方案 使用mysql数据库&#xff0c;使用一个字段来存储库存&#xff0c;每次扣减库存去更…

plex 乱码_Plex Media Center现在支持播客

plex 乱码Plex is adding beta support for podcasts to iOS, Android, Roku, and Plex Web today, alongside a custom home screen for mobile users. Plex现在为iOS&#xff0c;Android&#xff0c;Roku和Plex Web的播客添加了beta支持&#xff0c;同时为移动用户提供了自定…

ios12彻底关闭siri_Siri正在iOS 12中获取自定义语音操作

ios12彻底关闭siriSiri is about to get a lot more powerful. Custom voice commands for any app will allow you to say “Hey Siri, I lost my keys” to instantly launch an app that will help you find them. Siri将变得更加强大。 针对任何应用程序的自定义语音命令将…

过Postfix构建Exchange Server 2010邮件网关部署系列三:安装Exchange 2010先决性条件

1.将Exchange Server 2010服务器加入域。 2.在“开始”菜单上&#xff0c;依次导航到“所有程序”>“附件”>“Windows PowerShell”。打开提升的 Windows PowerShell 控制台并运行以下命令&#xff1a; Import-Module ServerManager 3.使用 Add-WindowsFeature cmdlet 安…

gmail收件箱标签设置_通过多个收件箱实验室有效管理您的Gmail

gmail收件箱标签设置Most people have more than one email account and if you are using Gmail it’s easy to get things set up so that all of your messages can be accessed in the same place. But if you would prefer to keep things ‘together yet separate’ the …

清华生命学院 2017 就业报告:就业率仅 51%

时间&#xff1a;20170406 一、截至目前生命学院整体就业情况 1.1 系统就业率 1.2 实际排查就业率 (6092)/(68230)51.06%二、本科生就业排查 2017 届本科生 68 人&#xff0c;已确定去向 60 人&#xff08;已登记去向 32 人&#xff09; 2.1 确定去向的 60 人中 国内深造 35 人…

程序改变了命运,程序生活一天比一天好,对未来也充满了希望

为什么80%的码农都做不了架构师&#xff1f;>>> 我出生在内蒙古自治区兴安盟扎赉特旗宝力根花苏木&#xff0c;那里是少数民族蒙古族聚居区&#xff0c;20-30年前与现代城市文明有些差距。当还在读小学的时在中学当数学老师的爸爸去深圳出差学习&#xff0c;顺路在…

powershell 变量_极客学院:学习PowerShell变量,输入和输出

powershell 变量As we move away from simply running commands and move into writing full blown scripts, you will need a temporary place to store data. This is where variables come in. 随着我们不再只是运行命令而转而编写完整的脚本&#xff0c;您将需要一个临时位…

offsetTop、offsetLeft、offsetWidth、offsetHeight、style中的样式

< DOCTYPE html PUBLIC -WCDTD XHTML StrictEN httpwwwworgTRxhtmlDTDxhtml-strictdtd> 假设 obj 为某个 HTML 控件。 obj.offsetTop 指 obj 距离上方或上层控件的位置&#xff0c;整型&#xff0c;单位像素。 obj.offsetLeft 指 obj 距离左方或上层控件的位置&#xff0…

Mock2 moco框架的http协议get方法Mock的实现

首先在Chapter7文件夹下再新建一个startGet.json startget.json代码如下&#xff0c;因为是get请求&#xff0c;所以要写method关键字&#xff0c;有两个&#xff0c;一个是有参数&#xff0c;一个是无参数的请求。 [{"description":"模拟一个没有参数的get请求…

imessage_如何在所有Apple设备上同步您的iMessage

imessageMessages in iCloud lets you sync your iMessages across all of your Apple devices using your iCloud account. Here’s how to set it up. 通过iCloud中的消息&#xff0c;您可以使用iCloud帐户在所有Apple设备上同步iMessage。 设置方法如下。 Apple announced t…

“.Net 社区大会”(dotnetConf) 2018 Day 1 主题演讲

Miguel de Icaza、Scott Hunter、Mads Torgersen三位大咖给大家带来了 .NET Core ,C# 以及 Xamarin的精彩内容&#xff1a;6月份已经发布了.NET Core 2.1, 大会上Scott Hunter 一开始花了大量的篇幅回顾.NET Core 2.1的发布&#xff0c;社区的参与度已经非常高&#xff0c;.NET…

长时间曝光计算_如何拍摄好长时间曝光的照片

长时间曝光计算In long exposure photography, you take a picture with a slow shutter speed—generally somewhere between five and sixty seconds—so that any movement in the scene gets blurred. It’s a way to show the passage of time in a single image. Let’s …

深度学习入门3

CNN 第一周&#xff1a; title: edge detection example 卷积核在边缘检测中的应用&#xff0c;可解释&#xff0c;卷积核的设计可以找到像素列突变的位置 把人为选择的卷积核参数&#xff0c;改为学习参数&#xff0c;可以学到更多的特征 title: padding n * n图片&#xff0c…

图像大小调整_如何在Windows中调整图像和照片的大小

图像大小调整Most image viewing programs have a built-in feature to help you change the size of images. Here are our favorite image resizing tools for Windows. We’ve picked out a built-in option, a couple of third party apps, and even a browser-based tool.…

Spring Data JPA例子[基于Spring Boot、Mysql]

阅读目录 关于Spring Data关于Spring Data子项目关于Spring Data Jpa例子&#xff0c;Spring Boot Spring Data Jpa运行、测试程序程序源码参考资料关于Spring Data Spring社区的一个顶级工程&#xff0c;主要用于简化数据&#xff08;关系型&非关系型&#xff09;访问&am…

The way of Webpack learning (IV.) -- Packaging CSS(打包css)

一&#xff1a;目录结构 二&#xff1a;webpack.config.js的配置 const path require(path);module.exports {mode:development,entry:{app:./src/app.js},output:{path:path.resolve(__dirname,dist),publicPath:./dist/,//设置引入路径在相对路径filename:[name].bundle.js…