首先在JSP頁面加上生成圖片的鏈接
<img type="image" src="auth/authCode" id="codeImage" name="codeImage" style="cursor:pointer;"/>,src需要我們自己實現,實現邏輯如下
運行后,jsp頁面會發出"auth/code"請求生成驗證碼,並將驗證碼放置於session中用於驗證,運行效果如下
我們在jsp頁面上加上輸入驗證碼的輸入框及提交按鈕,點擊按鈕后進行驗證碼判斷
后台會比將收入的驗證碼與放置於session中的驗證碼進行比對,並輸出結果給JSP頁面進行相應處理,當判斷為失敗,則刷新驗證碼
最后,相對完整的頁面和邏輯都已實現,代碼如下
JSP頁面代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ page import="java.util.*" %>
<html>
<head>
<title>Title</title>
</head>
<%--<script src="js/jquery.min.js"></script>--%>
<script src="https://libs.baidu.com/jquery/1.8.3/jquery.js"></script>
<script type="text/javascript">
function submitForm() {
var inputCode=$("#authCode").attr("value");
var list={"inputCode":inputCode};
$.ajax({
//請求方式
type : "POST",
//請求的媒體類型
contentType: "application/x-www-form-urlencoded",
//請求地址
url : "auth/checkCode",
//數據,json字符串
data :list,
dataType:"json",
//請求成功
success : function(result) {
alert(result);
if(result=="1"){
alert("驗證通過");
}else{
alert("驗證失敗,重新刷新驗證碼");
flushAuthCode();
}
},
//請求失敗,包含具體的錯誤信息
error : function(e){
alert(e.responseText);
}
});
}
function flushAuthCode() {
//重新刷新驗證碼
$("#codeImage").attr("src","auth/authCode?abc="+Math.random());
}
</script>
<body>
<form id="authForm" action="checkCode">
<input type="text" id="authCode" name="authCode">
<img type="image" src="auth/authCode" id="codeImage" name="codeImage" style="cursor:pointer;"/>
<button type="button" id="submitBtn" name="submitBtn" value="提交" onclick="submitForm()"/>
</form>
</body>
</html>
后台代碼
package com.founderit.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@Controller
@RequestMapping("auth")
public class Auth {
private char[] codeSequence = { 'A', '1','B', 'C', '2','D','3', 'E','4', 'F', '5','G','6', 'H', '7','I', '8','J',
'K', '9' ,'L', '1','M', '2','N', 'P', '3', 'Q', '4', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'};
@RequestMapping("authCode")
public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
int width = 63;
int height = 37;
Random random = new Random();
//設置response頭信息
//禁止緩存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//生成緩沖區image類
BufferedImage image = new BufferedImage(width, height, 1);
//產生image類的Graphics用於繪制操作
Graphics g = image.getGraphics();
//Graphics類的樣式
g.setColor(this.getColor(200, 250));
g.setFont(new Font("Times New Roman",0,28));
g.fillRect(0, 0, width, height);
//繪制干擾線
for(int i=0;i<40;i++){
g.setColor(this.getColor(130, 200));
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x, y, x + x1, y + y1);
}
//繪制字符
String strCode = "";
for(int i=0;i<4;i++){
String rand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
strCode = strCode + rand;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(rand, 13*i+6, 28);
}
//將字符保存到session中用於前端的驗證
session.setAttribute("authCode", strCode.toLowerCase());
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
response.getOutputStream().flush();
}
public Color getColor(int fc,int bc){
Random random = new Random();
if(fc>255)
fc = 255;
if(bc>255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r,g,b);
}
@RequestMapping(value = "checkCode",method = RequestMethod.POST)
@ResponseBody
public String checkAuthCode(@RequestParam(value = "inputCode") String inputCode, HttpServletRequest request){
String checkCode=(String) request.getSession().getAttribute("authCode");
//返回1 代表判斷通過,0代表失敗
String isCode=checkCode.equals(inputCode)?"1":"0";
return isCode;
}
}