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,null,?new?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.pswp.cn/news/279406.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279406.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279406.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

馬云:未來無工可打,人工智能發展紅利還在10年以后

馬云雖然已經退出阿里巴巴&#xff0c;但作為一代商業傳奇他所說的話&#xff0c;還十分據有影響力。關于人工智能&#xff0c;馬云提出過不少預測性言論。未來10年&#xff0c;房子、車子都不在值錢。面對人工智能時代&#xff0c;未來傳統行業大部分會消失。更有厲害的&#…

如何更改您的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;每個…

【ACM-ICPC 2018 沈陽賽區網絡預賽 I】Lattice's basics in digital electronics

【鏈接】 我是鏈接,點我呀:) 【題意】 【題解】 每個單詞的前綴都不同。 不能更明示了... 裸的字典樹。 模擬一下。輸出一下就ojbk了。 【代碼】 #include <bits/stdc.h> #define LL long long #define rep1(i,a,b) for (int i a;i < b;i) #define rep2(i,a,b) for…

扒一扒那些年我們遇到的奇葩代碼

前言 本文首發于公眾號【一名打字員】 在工作中&#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;每次扣減庫存去更…

JavaScript 使用random()生成隨機數

function myFunction() { var a Math.floor(Math.random()*10);return a;} // 記住 Math.random() 永遠不會返回 1。同時因為我們是在用 Math.floor() 向下取整&#xff0c;所以最終我們獲得的結果不可能有 20。這確保了我們獲得了一個在0到19之間的整數。 把操作連綴起來&…

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;同時為移動用戶提供了自定…

Add a All Document Folder

本文出自Simmy的個人blog&#xff1a;西米在線 http://simmyonline.com/archives/54.html right clickSearch Folder-New Search Folder-Custom-Create a custom folder 本文轉simmy51CTO博客&#xff0c;原文鏈接&#xff1a;http://blog.51cto.com/helpdesk/122327&#xff0…

Oracle服務器修改IP后

機房有兩套網絡&#xff0c;一套辦公網&#xff0c;一套機房的內網&#xff0c;辦公網可以通過vpn在其他地方訪問&#xff0c;內網只能在公司辦公室訪問。團隊有同事去外地辦公&#xff0c;開發的時候需要通過客戶端直連數據庫&#xff0c;于是把數據庫服務器的網線換到辦公網的…

代理IP對直播平臺的影響與關系-國內多IP曇花一現

1.代理IP的作用1>.訪問一些單位或團體內部資源&#xff0c;如某大學FTP(前提是該代理地址在該資源 的允許訪問范圍之內)&#xff0c;使用網絡內地址段免費代理服務器&#xff0c;就可以用于對 網絡開放的各類FTP下載上傳&#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將變得更加強大。 針對任何應用程序的自定義語音命令將…

spring cloud連載第一篇之bootstrap context

1. Spring Cloud Context: Application Context Services&#xff08;應用上下文服務&#xff09; 1.1 The Bootstrap Application Context&#xff08;引導上下文&#xff09; 一個spring cloud應用會創建一個“bootstrap”context&#xff0c;它是主應用的parent context。它…

過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請求…