JavaEE----登陆界面验证码实现
主要使用后端验证,调用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域,当用户提交请求时,获取表单数据然后进行比对<(^-^)>
效果图
提供的代码尽量以参考为主,如有疑问,欢迎提出