Spring MVC 驗證碼

頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

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>My JSP 'code.jsp' starting page</title>

? ??

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0"> ? ?

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script src="js/jquery-1.7.2.min.js"></script>

<script type="text/javascript">

?function changeImg() {

? var imgSrc = $("#imgObj");

? var src = imgSrc.attr("src");

? //alert(src);

? imgSrc.attr("src", chgUrl(src));

? alert($("#code").val());

? //$("#code").val("123456");?

? //<c:out value="${sessionScope.code}"/>

?}

?//時間戳 ?

?//為了使每次生成圖片不一致,即不讓瀏覽器讀緩存,所以需要加上時間戳 ?

?function chgUrl(url) {

? var timestamp = (new Date()).valueOf();

? url = url.substring(0, 17);

? if ((url.indexOf("&") >= 0)) {

? ?url = url + "×tamp=" + timestamp;

? } else {

? ?url = url + "?timestamp=" + timestamp;

? }

? return url;

?}

?function refresh(obj) {

? ? ? ? obj.src = "code.html";

? ? }

</script>

? </head>

??

? <body>?

? ? ? ? 驗證碼<input id="index_code" name="code" type="text" />?

? ? ? ? <img id="imgObj" alt="驗證碼" src="code.html" οnclick="javascript:changeImg();" />?

? ? ? ? <!-- <a href="" οnclick="changeImg()"οnclick="javascript:refresh(this);">換一張</a> -->

? ? ? ? <input type="button" οnclick="javascript:changeImg();" value="看不清換一張">

? ? ? ? <input type="hidden" value="123456" id="code"/>

? </body>

</html>

后臺

/**

?* 用戶驗證碼

?* @author Administrator

?*

?*/

@Controller

public class CodeController {

private int width = 90;//定義圖片的width ?

? ?private int height = 20;//定義圖片的height ?

? ?private int codeCount = 4;//定義圖片上顯示驗證碼的個數 ?

? ?private int xx = 15;?

? ?private int fontHeight = 18;?

? ?private int codeY = 16;?

? ?char[] codeSequence = {?

? ? 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',

? ? 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

? ? '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };?

?

? ?@RequestMapping("/code")?

? ?public void getCode(HttpServletRequest req, HttpServletResponse resp)?

? ? ? ? ? ?throws IOException {?

?

? ? ? ?// 定義圖像buffer ?

? ? ? ?BufferedImage buffImg = new BufferedImage(width, height,?

? ? ? ? ? ? ? ?BufferedImage.TYPE_INT_RGB);?

? ? ? ?//Graphics2D gd = buffImg.createGraphics(); ?

? ? ? ?//Graphics2D gd = (Graphics2D) buffImg.getGraphics(); ?

? ? ? ?Graphics gd = buffImg.getGraphics();?

? ? ? ?// 創建一個隨機數生成器類 ?

? ? ? ?Random random = new Random();?

? ? ? ?// 將圖像填充為白色 ?

? ? ? ?gd.setColor(Color.WHITE);?

? ? ? ?gd.fillRect(0, 0, width, height);?

?

? ? ? ?// 創建字體,字體的大小應該根據圖片的高度來定。 ?

? ? ? ?Font font = new Font("Fixedsys", Font.BOLD, fontHeight);?

? ? ? ?// 設置字體。 ?

? ? ? ?gd.setFont(font);?

?

? ? ? ?// 畫邊框。 ?

? ? ? ?gd.setColor(Color.BLACK);?

? ? ? ?gd.drawRect(0, 0, width - 1, height - 1);?

?

? ? ? ?// 隨機產生40條干擾線,使圖象中的認證碼不易被其它程序探測到。 ?

? ? ? ?gd.setColor(Color.BLACK);?

? ? ? ?for (int i = 0; i < 40; i++) {?

? ? ? ? ? ?int x = random.nextInt(width);?

? ? ? ? ? ?int y = random.nextInt(height);?

? ? ? ? ? ?int xl = random.nextInt(12);?

? ? ? ? ? ?int yl = random.nextInt(12);?

? ? ? ? ? ?gd.drawLine(x, y, x + xl, y + yl);?

? ? ? ?}?

?

? ? ? ?// randomCode用于保存隨機產生的驗證碼,以便用戶登錄后進行驗證。 ?

? ? ? ?StringBuffer randomCode = new StringBuffer();?

? ? ? ?int red = 0, green = 0, blue = 0;?

?

? ? ? ?// 隨機產生codeCount數字的驗證碼。 ?

? ? ? ?for (int i = 0; i < codeCount; i++) {?

? ? ? ? ? ?// 得到隨機產生的驗證碼數字。 ?

? ? ? ? ? ?String code = String.valueOf(codeSequence[random.nextInt(62)]);?

? ? ? ? ? ?// 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。 ?

? ? ? ? ? ?red = random.nextInt(255);?

? ? ? ? ? ?green = random.nextInt(255);?

? ? ? ? ? ?blue = random.nextInt(255);?

?

? ? ? ? ? ?// 用隨機產生的顏色將驗證碼繪制到圖像中。 ?

? ? ? ? ? ?gd.setColor(new Color(red, green, blue));?

? ? ? ? ? ?gd.drawString(code, (i + 1) * xx, codeY);?

?

? ? ? ? ? ?// 將產生的四個隨機數組合在一起。 ?

? ? ? ? ? ?randomCode.append(code);?

? ? ? ?}?

? ? ? ?// 將四位數字的驗證碼保存到Session中。 ?

? ? ? ?HttpSession session = req.getSession();?

? ? ? ?System.out.println(randomCode);?

? ? ? ?session.setAttribute("code", randomCode.toString());?

?

? ? ? ?// 禁止圖像緩存。 ?

? ? ? ?resp.setHeader("Pragma", "no-cache");?

? ? ? ?resp.setHeader("Cache-Control", "no-cache");?

? ? ? ?resp.setDateHeader("Expires", 0);?

?

? ? ? ?resp.setContentType("image/jpeg");?

?

? ? ? ?// 將圖像輸出到Servlet輸出流中。 ?

? ? ? ?ServletOutputStream sos = resp.getOutputStream();?

? ? ? ?ImageIO.write(buffImg, "jpeg", sos);?

? ? ? ?sos.close();?

? ?}?

/**********************************調到驗證碼**************************************/

@RequestMapping("/tocode")

public ModelAndView tologin(HttpServletRequest request,HttpServletResponse response) {

ModelAndView mav = new ModelAndView();

mav.setViewName("/user/code");

return mav;

}

}


本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273513.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273513.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273513.shtml

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

相關文章

數據結構實驗之鏈表四:有序鏈表的歸并

數據結構實驗之鏈表四&#xff1a;有序鏈表的歸并 Time Limit: 1000MS Memory limit: 65536K 題目描述 分別輸入兩個有序的整數序列&#xff08;分別包含M和N個數據&#xff09;&#xff0c;建立兩個有序的單鏈表&#xff0c;將這兩個有序單鏈表合并成為一個大的有序單鏈表&…

apk文件編譯到系統文件中的方法(及包含so庫的)

把第三方或自己開發的apk文件編譯到系統文件(system.img)中的方法&#xff1a; 1 (1)源碼編譯后&#xff0c;把apk拷貝到out\target\product\generic\system\app中。 (2) 執行命令make snod , 把添加的spk編到system.img 中 缺點&#xff1a;執行make clean 后&#xff0c;再…

javascript中interval與setTimeOut的區別

setTimeout(code,millisec) //- 在指定時間后執行代碼 code必須&#xff1b; millisec必須&#xff1b; clearTimeout(setTimeoutId) //- 取消 setTimeout() setInterval(code,millisec)&#xff1b;//指定間隔毫秒內循環執行代碼 code必須&#xff1b; millisec必須&a…

java設計模式之單例模式(七種方法)

單例模式&#xff1a;個人認為這個是最簡單的一種設計模式&#xff0c;而且也是在我們開發中最常用的一個設計模式。 單例模式的意思就是只有一個實例。單例模式確保某一個類只有一個實例&#xff0c;而且自行實例化并向整個系統提供這個實例。這個類稱為單例類。我們前面學習的…

java 遍歷map集合

Map<String, String> map new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); //第一種&#xff1a;通過Map.keySet遍…

poj3009 Curling 2.0 深搜

PS&#xff1a;以前看到題目這么長就沒寫下去了。今天做了半天&#xff0c;沒做出來。準備看題解&#xff0c;打開了網站都忍住了&#xff0c;最后還是靠自己做出來的。算是一點進步吧。 分析&#xff1a; 題目的意思沒明白或者理解有偏差都沒辦法做題。看樣例3和樣例4&#xf…

Android監聽事件

ListView事件監聽&#xff1a; setOnItemSelectedListener 鼠標滾動時觸發 setOnItemClickListener 點擊時觸發 EditText事件監聽&#xff1a; setOnKeyListener 獲取焦點時觸發 RadioGroup事件監聽&#xff1a; setOnCheckedChangeListener 點擊時觸發 CheckBox事件監聽&#…

子類能不能繼承父類的構造方法?

class A{ public A(){} // 1:無參數構造方法。 public A(String s){} // 2.}class B extends A{ public B(String s){ super(s); // 3. }}說明&#xff1a;如果沒有1處的無參數構造方法&#xff0c;那么3處一定要主動調用父類帶參數的構造方法。如果有1處的構造方法&#…

基于原生javascript的ajax實現

function getXMLHttpRequest(){if(window.ActiveXObject){//用戶是ie瀏覽器http_requestnew ActiveXObject("Microsoft.XMLHTTP");}else{//其他的瀏覽器http_requestnew XMLHttpRequest();}return http_request;}var httpRequest;function name(){httpRequestgetXMLH…

Google File System設計方面的問題匯總

1、Google File System概述 google file system是一個分布式文件系統&#xff0c;針對的是數據密集型應用&#xff0c;提供容錯功能&#xff0c;運行在低廉的服務器上&#xff0c;同時給大量的用戶提供高性能服務。盡管google file system有著傳統的分布式文件系統的目標&#…

linux phpize

phpize是什么 1、phpize是用來擴展php擴展模塊的&#xff0c;通過phpize可以建立php的外掛模塊。 當php編譯完后&#xff0c;在bin下面會有phpize這個腳本文件&#xff0c; 在編譯你要添加的擴展模塊之前&#xff0c;執行以下phpize就可以了&#xff1b; 比如現在想在php中加入…

一些常用的正則表達式

較驗郵箱&#xff1a; var EmailReg /^[-_A-Za-z0-9]([_A-Za-z0-9]\.)[A-Za-z0-9]{2,3}$/; 身份證號碼&#xff1a; var reg /(^\d{15}$)|(^\d{17}(\d|X)$)/; 15位身份證號 //身份證15位時&#xff0c;次序為省&#xff08;3位&#xff09;市&#xff08;3位&#xff…

iOS iphone屏幕分析(豈止而大)

在寫本文前&#xff0c;我必須介紹幾點內容&#xff1a;第一點&#xff1a;屏幕上面顯示的內容多少和屏幕的尺寸大小無關第二點&#xff1a;屏幕上面顯示的內容多少和分辨率完全無關第三點&#xff1a;屏幕上面顯示的內容多少和屏幕尺寸、屏幕分辨率、PPI等都是無關的那到底什么…

js的一些實現

響應回車鍵提交表單 //*******************************************************響應回車鍵登錄****************************************************************** document.οnkeydοwnfunction(event){ var e event || window.event || arguments…

【隨筆】Win7下GVIM的安裝與配置

針對各種語言的編輯器千千萬萬&#xff0c;最好的就是最適合自己的&#xff0c;這句話一點沒錯。 偶然間&#xff0c;需要在Windows上編寫代碼&#xff0c;MyEclipse等太大&#xff0c;完全沒有必要&#xff0c;所以就想起來了vim這個神器。個子小&#xff0c;功能強&#xff0…

java遍歷Set集合

在Java中使用Set,可以方便地將需要的類型&#xff0c;以集合類型保存在一個變量中.主要應用在顯示列表. Set是一個不包含重復元素的collection。更確切地講&#xff0c;set 不包含滿足 e1.equals(e2) 的元素對 e1 和 e2&#xff0c;并且最多包含一個 null 元素。 import java.u…

Java switch語句

在Java7之前&#xff0c;switch只能支持 byte、short、char、int或者其對應的封裝類以及Enum類型。 Java7可以使用String作為判斷條件 public class Test { public void test(String str) { switch(str) { case "abc": …

find之exec和args

本來以為以前的差不多夠用了。呵呵&#xff0c;看到很多高手用高技巧&#xff0c;心癢癢的覺得我自己還可以提升啊。。哈哈哈。 這個實踐起來之后&#xff0c;&#xff0c;SED,AWK也得深化一下&#xff0c;&#xff0c;&#xff0c;SHELL和PYTHON&#xff0c;作運維的兩樣都不能…

Java 字符串分割陷阱

Java中關于字符串有一個split方法&#xff0c;這個方法可以實現分割字符串的作用&#xff1b; 但是如果使用一些正則表達式中出現的字符時Java編譯器會報錯&#xff0c; 如&#xff1a; String str "com.zhangsan.lisi.wangwu"; String[] strArray str.split(…

Linux 復習重點目錄

Linux安全復習 一、Linux基本命令 1、文件管理命令 lvm 2、用戶管理命令 3、網絡管理命令 4、權限管理 普通權限和特殊權限 權限命令修改 5、服務命令 6、軟件安裝管理命令 yum安裝 prm包安裝 源碼包安裝 7、vim 、cat 、more、less文件處理 8、進程管理 top、ps、計劃任務、守…