主要使用后端驗證,調用awt API ,會簡單調用即可,繪圖代碼已封裝到LoginVerifyUtils中。
界面展示:
LoginVerifyUtils全部代碼
1 import java.awt.Color; 2 import java.awt.Font; 3 import java.awt.Graphics2D; 4 import java.awt.font.FontRenderContext; 5 import java.awt.geom.Rectangle2D; 6 import java.awt.image.BufferedImage; 7 import java.io.ByteArrayOutputStream; 8 import java.io.IOException; 9 import java.util.Random; 10 11 import javax.imageio.ImageIO; 12 13 public class LoginVerifyUtils { 14 15 private static LoginVerifyUtils loginVerifyUtils = new LoginVerifyUtils(); 16 17 private LoginVerifyUtils() { 18 } 19 20 public static LoginVerifyUtils getInstance() { 21 return loginVerifyUtils; 22 } 23 24 /** 25 * 繪畫驗證碼 26 * @param output 27 * @return 28 */ 29 public String drawImg(ByteArrayOutputStream output) { 30 String code = ""; 31 // 隨機產生4個字符 32 for (int i = 0; i < 4; i++) { 33 code += randomChar(); 34 } 35 int width = 70; 36 int height = 25; 37 BufferedImage bi = new BufferedImage(width, height, 38 BufferedImage.TYPE_3BYTE_BGR); 39 Font font = new Font("Times New Roman", Font.PLAIN, 20); 40 // 調用Graphics2D繪畫驗證碼 41 Graphics2D g = bi.createGraphics(); 42 g.setFont(font); 43 Color color = new Color(66, 2, 82); 44 g.setColor(color); 45 g.setBackground(new Color(226, 226, 240)); 46 g.clearRect(0, 0, width, height); 47 FontRenderContext context = g.getFontRenderContext(); 48 Rectangle2D bounds = font.getStringBounds(code, context); 49 double x = (width - bounds.getWidth()) / 2; 50 double y = (height - bounds.getHeight()) / 2; 51 double ascent = bounds.getY(); 52 double baseY = y - ascent; 53 g.drawString(code, (int) x, (int) baseY); 54 g.dispose(); 55 try { 56 ImageIO.write(bi, "jpg", output); 57 } catch (IOException e) { 58 e.printStackTrace(); 59 } 60 return code; 61 } 62 63 /** 64 * 隨機獲取一個字符 65 * @return 66 */ 67 public char randomChar() { 68 Random r = new Random(); 69 String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789"; 70 return s.charAt(r.nextInt(s.length())); 71 } 72 }
login.jsp
<div id="login">
<div class="form-inline" >
<div class="input-group">
<span class="input-group-addon">賬號</span>
<input type="text" class="form-control" name="id" id="adminId">
</div><br/><br/>
<div class="input-group">
<span class="input-group-addon">密碼</span>
<input type="password" class="form-control" name="passwd" id="passwd">
</div>
<br/><br/>
<div class="input-group">
<span class="code_img"> <img
src="${APP_PATH}/admin/getVerifyCode"
width="110" height="40" id="verifyCodeImage">
</span><a id="changeVerifImageRegister"
onclick="javascript:changeImage();">換一張</a>
</div>
<br/><br/>
<div class="input-group">
<span class="input-group-addon">驗證碼</span>
<input type="text" class="form-control" name="verifyCode" style="width: 184px" id="verifyCode">
</div><br/>
<p style="text-align: right;color: red;position: absolute" id="info"></p>
<br/>
<button id="loginButton" class="btn btn-primary">登陸
</button>
</div>
依賴ui庫
<link rel="stylesheet" href="${APP_PATH }/static/css/bootstrap.min.css"> <script src="${APP_PATH }/static/js/jquery-3.2.1.min.js"></script> <script src="${APP_PATH }/static/js/bootstrap.min.js"></script>
javascript
$("#loginButton").click(function () {
if($("#adminId").val()==''&&$("#passwd").val()==''){
$("#info").text("提示:賬號和密碼不能為空");
}
else if ($("#adminId").val()==''){
$("#info").text("提示:賬號不能為空");
}
else if($("#passwd").val()==''){
$("#info").text("提示:密碼不能為空");
}else if($("#verifyCode").val()==''){
$("#info").text("提示:請輸入驗證碼");
}
else {
//驗證碼
$.ajax({
type: "GET",
url: "${APP_PATH}/admin/verifyCode",
data: {
verifyCode:$("#verifyCode").val() ,
},
dataType: "json",
success: function(data) {
if(data.stateCode.trim() == "1003") {
$("#info").text("提示:服務器異常");
flag = false;
} else if(data.stateCode.trim() == "1002") {
$("#info").text("提示:驗證碼錯誤");
} else{
userLogin()
}
}
});
}
})
function userLogin(){
$.ajax({
type: "POST",
url: "${APP_PATH}/admin/login",
data: {
username:$("#adminId").val() ,
password: $("#passwd").val()
},
dataType: "json",
success: function(data) {
if(data.stateCode.trim() == "1003") {
$("#info").text("提示:該用戶不存在");
} else if(data.stateCode.trim() == "1002") {
$("#info").text("提示:密碼錯誤");
} else if(data.stateCode.trim() == "1001"){
$("#info").text("提示:登陸成功,跳轉中...");
window.location.href="${APP_PATH}/main";
}else{
$("#info").text("提示:服務器出錯");
}
}
});
}
loginController參考
/** * 獲取驗證碼 * @param response * @param session */ @GetMapping("/getVerifyCode") public void generate(HttpServletResponse response, HttpSession session) { ByteArrayOutputStream output = new ByteArrayOutputStream(); LoginVerifyUtils loginVerifyUtils = LoginVerifyUtils.getInstance(); String verifyCodeValue =loginVerifyUtils.drawImg(output); session.setAttribute("verifyCodeValue", verifyCodeValue); try { ServletOutputStream out = response.getOutputStream(); output.writeTo(out); } catch (IOException e) { e.printStackTrace(); } } //驗證 @GetMapping("/verifyCode") public @ResponseBody AJAXResult verifyCode(@RequestParam("verifyCode") String verifyCode ,HttpSession session) { AJAXResult result = new AJAXResult(); try { String verifyCodeValue = (String) session.getAttribute("verifyCodeValue"); if(verifyCode.trim().toUpperCase().equals(verifyCodeValue)) { result.setStateCode("1001"); } } catch (Exception e) { e.printStackTrace(); result.setStateCode("1003"); } return result; } @ResponseBody @PostMapping("/login") public Object login(Admin admin ,HttpServletRequest request) { AJAXResult result = new AJAXResult(); try { Wrapper<Admin> wrapper = new EntityWrapper<Admin>(); wrapper.eq("username", admin.getUsername()); boolean isName = adminService.selectOne(wrapper) == null ? true: false; if(isName) { result.setStateCode("1003");//用戶名不存在 }else { Wrapper<Admin> wrapper2 = new EntityWrapper<Admin>(); wrapper2.eq("username", admin.getUsername()); wrapper2.eq("password", admin.getPassword()); Admin loginAdmin = adminService.selectOne(wrapper2); if(loginAdmin != null ) { request.getSession().setAttribute("loginAdmin", loginAdmin); LoginLog loginLog = new LoginLog(); loginLog.setAdminId(loginAdmin.getId()); loginLog.setLoginDate(new Date() ); loginLog.setLoginIp(request.getRemoteAddr()); loginLogService.insert(loginLog ); result.setStateCode( "1001");//登陸成功 }else { result.setStateCode( "1002");//用戶名或密碼錯誤 } } } catch (Exception e) { e.printStackTrace(); result.setStateCode( "1004");//服務器出錯 } return result ; }
ps:主要邏輯就是把隨機生成的驗證碼放到session域,當用戶提交請求時,獲取表單數據然后進行比對<(^-^)>
效果圖


提供的代碼盡量以參考為主,如有疑問,歡迎提出

