最終效果展示:

代碼展示:
1、前端登錄頁面代碼展示
<div class="form-group">
<div class="input-icon">
<i class="fa fa-picture-o"></i>
<input class="form-control" style="width:180px;" type="text" id="verifyCode" name="verifyCode" placeholder="驗證碼" maxlength="4">
<img style="position: absolute;right: 0;top: 0;" src="${pageContext.request.contextPath }/user/getVerifyCode" width="110" height="34" id="verifyCodeImage" onclick="javascript:changeImage();">
</div>
</div>
/*點擊圖片更換驗證碼事件*/
function changeImage() {
$('#verifyCodeImage').attr('src', '${pageContext.request.contextPath }/user/getVerifyCode);
}
2、點擊登錄之后進行controller代碼展示
//驗證碼驗證思路,其實就是后台生成一個隨機數保存到session中並且顯示到頁面,用戶輸入的驗證碼與session中保存的隨機數進行忽略大小寫的比較,如果相同就驗證成功,否則失敗。
/* 獲取校驗碼 */
@RequestMapping("/getVerifyCode")
public void generate(HttpServletResponse response, HttpSession session) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
String verifyCodeValue = drawImg(output);
// 將校驗碼保存到session中
session.setAttribute("verifyCodeValue", verifyCodeValue);
try {
ServletOutputStream out = response.getOutputStream();
output.writeTo(out);
} catch (IOException e) {
logger.info("<--驗證碼前端寫出.出現異常-->");
e.printStackTrace();
}
}
/* 繪制驗證碼 */
private String drawImg(ByteArrayOutputStream output) {
String code = "";
// 隨機產生4個字符
for (int i = 0; i < 4; i++) {
code += randomChar();
}
int width = 70;
int height = 25;
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_3BYTE_BGR);
Font font = new Font("Times New Roman", Font.PLAIN, 20);
// 調用Graphics2D繪畫驗證碼
Graphics2D g = bi.createGraphics();
g.setFont(font);
Color color = new Color(66, 2, 82);
g.setColor(color);
g.setBackground(new Color(226, 226, 240));
g.clearRect(0, 0, width, height);
FontRenderContext context = g.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(code, context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = bounds.getY();
double baseY = y - ascent;
g.drawString(code, (int) x, (int) baseY);
g.dispose();
try {
ImageIO.write(bi, "jpg", output);
} catch (IOException e) {
e.printStackTrace();
}
return code;
}
/* 獲取隨機參數 */
private char randomChar() {
Random r = new Random();
String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
return s.charAt(r.nextInt(s.length()));
}
//這段代碼放到你的登錄請求中,獲取用戶輸入的校驗碼並進行比較
String verifyCode = request.getParameter("verifyCode"); String sessionVerifyCode = (String) session.getAttribute("verifyCodeValue"); if (!verifyCode.equalsIgnoreCase(sessionVerifyCode)) { logger.info("<--登錄失敗,驗證碼輸入有誤!-->"); redirectAttributes.addFlashAttribute("message", "驗證碼輸入有誤!"); return "redirect:/user/login"; }

