java spring 實現登入頁面新增驗證碼
from 表單:
<div class="block">
<p class="block-heading">使用者登入</p>
<div class="block-body">
<form id="login_form"
action="${pageContext.request.contextPath}/platform/login.htm"
method="post">
<input type="hidden" name="remFlag" id="remFlag"/>
<label>使用者名稱</label>
<input autocomplete="off" id="username" name="username" value="${userName}" type="text" placeholder="請輸入使用者名稱" class="span12">
<label>密碼</label>
<input name="password" id="password" type="password" class="span12" autocomplete="off" value="${userPass}" placeholder="請輸入用密碼" >
<label>驗證碼</label>
<input autocomplete="off" style="width: 150px;" id="code" name="code" type="text" placeholder="請輸入驗證碼" class="span12" onblur="document.getElementById('enter').focus();">
<img alt="驗證碼" id="scode" style="width: 75px; height:30px; margin-bottom: 9px; " src="${pageContext.request.contextPath}/platform/getCode.htmc" >
<a href="#" onclick="javascript:flushCode();"><font style="font-style:italic;" size="1">看不清?換一張</font></a><br>
<input name="aaaa" type="checkbox" onclick="remember();">記住賬號和密碼
<a id="enter" href="#*" class="btn btn-primary pull-right" onclick="toLogin()">立即登入</a>
</form>
</div>
</div>
js:
function flushCode() {
// 每次重新整理的時候獲取,防止瀏覽器快取重新整理失敗
var time = Math.random();
document.getElementById("scode").src = "${pageContext.request.contextPath}/platform/getCode.htmc?time=" + time;
}
後臺controller:
/**
* 生成驗證碼
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/platform/getCode")
public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
int IMG_HEIGHT = 100;
int IMG_WIDTH = 40;
// 用於繪製圖片,設定圖片的長寬和圖片型別(RGB)
BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
// 獲取繪圖工具
Graphics graphics = bi.getGraphics();
graphics.setColor(new Color(180, 200, 200)); // 使用RGB設定背景顏色
graphics.fillRect(0, 0, 100, 40); // 填充矩形區域
// 驗證碼中所使用到的字元
char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
String captcha = ""; // 存放生成的驗證碼
Random random = new Random();
for(int i = 0; i < 4; i++) { // 迴圈將每個驗證碼字元繪製到圖片上
int index = random.nextInt(codeChar.length);
graphics.setFont(new Font("黑體", Font.BOLD, 20));
// 隨機生成驗證碼顏色
graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
// 將一個字元繪製到圖片上,並制定位置(設定x,y座標)
graphics.drawString(codeChar[index] + "", (i * 20) + 15, 30);
captcha += codeChar[index];
}
for (int i = 0; i < 20; i++) {
int x = random.nextInt(IMG_HEIGHT);
int y = random.nextInt(IMG_WIDTH);
int xl = random.nextInt(20);
int yl = random.nextInt(20);
graphics.drawLine(x, y, x + xl, y + yl);
}
// 將生成的驗證碼code放入sessoin中
request.getSession().setAttribute("code", captcha);
// 通過ImageIO將圖片輸出
ImageIO.write(bi, "JPG", response.getOutputStream());
}