1. 程式人生 > >隨機生成數字與字母驗證碼_簡易版

隨機生成數字與字母驗證碼_簡易版

由於我還是初學者,並沒有考慮到是否安全這方面。有什麼錯誤的或者不好的,歡迎大家指出,便於我及時改正。謝謝!

首先寫一個隨機生成字串的方法

//length為產生的位數
public static String getRandomString(int length) {
	// 定義一個字串(A-Z,a-z,0-9)即62位;
    String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
	// 由Random生成隨機數
	Random random = new Random();
	StringBuffer sb = new StringBuffer();
	// 長度為幾就迴圈幾次
	for (int i = 0; i < length; ++i) {
		// 產生0-61的數字
		int number = random.nextInt(62);
		// 返回指定索引的字元
		sb.append(str.charAt(number));
	}
	return sb.toString();
}

 然後就是呼叫這個方法了。

在這裡我使用的是springMvc。當然也可以使用Servlet來呼叫,呼叫的方式也是一樣的,這裡我就不多說了。

@Controller
public class TestCode {
 
	@RequestMapping("/getCode.action")
	@ResponseBody
	public String getCode() {
        //呼叫幫助類裡面的隨機生成字串方法,傳入的引數為要生成的字串的長度
		return CharacterUtils.getRandomString(4);
	}
 
	@RequestMapping("/testCode")
	public String testCode() {
		return "test";
	}
 
}

呼叫完了接下來就是jsp頁面顯示了

在這裡我對驗證碼字串做了一些樣式調整

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<style type="text/css">
#testimg {
    text-align: center;
    background-color: #F44336;
    color: white;
    font-style: italic;
    font-family: fantasy;
    width: 40px;
    content: initial;
    display: -webkit-inline-box;
}
</style>
</head>
<body>
	使用者名稱:<input type="text" name="name" id="name"><br /> 
	密 碼:<input type="text" name="pwd" id="pwd"><br /> 
	驗證碼:<input type="text" id="inputCode">
	<div id="code"></div><a href="#" onclick="getCode()" style="font-size: 10px;">看不清</a><br />
	<input type="submit" value="提交" id="submit">
</body>
 
<script type="text/javascript">
 
$(function() {
	getCode();
})
 
function getCode() {
	$.ajax({
		data : "get",
		typeData : "json",
		url : "getCode.action",
		success : function(result) {
			$("#testimg").html(result);
		},
		error : function(result) {
			alert(result);
		}
	})
};
$("#submit").click(function() {
		var inputCode = $("#inputCode").val();
		var code = $("#code").text()
		if (inputCode == code) {
			alert("驗證碼成功!");
		} else {
			alert("驗證失敗");
			alert("inputCode-->" + inputCode);
			alert("Code-->" + Code);
		}
	});
</script>
 
</html>

總的來說,我寫的這個功能非常的簡單。實用不實用,這個我就不知道了,但是也算是完成了驗證碼這個功能。

由於我也是初學者,考慮的也不周全,請各位大神輕點噴。