JavaEE----登陆界面验证码实现

主要使用后端验证,调用awt API ,会简单调用即可,绘图代码已封装到LoginVerifyUtils中。

界面展示:

LoginVerifyUtils全部代码

图片描述

图片描述

 import java.awt.Color;
 import java.awt.Font;
 import java.awt.Graphics2D;
 import java.awt.font.FontRenderContext;
 import java.awt.geom.Rectangle2D;
 import java.awt.image.BufferedImage;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.util.Random;
 
 import javax.imageio.ImageIO;
 
 public class LoginVerifyUtils {
 
     private static LoginVerifyUtils loginVerifyUtils = new LoginVerifyUtils(); 
 
     private LoginVerifyUtils() {
     }
     
     public static LoginVerifyUtils getInstance() {
         return loginVerifyUtils;
     }
     
     /**
      * 绘画验证码
      * @param output
      * @return
      */
     public 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;
     }
     
     /**
      * 随机获取一个字符
      * @return
      */
     public char randomChar() {
         Random r = new Random();
         String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
         return s.charAt(r.nextInt(s.length()));
     }
 }

View Code

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>

<div class="input-group"> <span class="input-group-addon">密码</span> <input type="password" class="form-control" name="passwd" id="passwd"> </div>

<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>

<div class="input-group"> <span class="input-group-addon">验证码</span> <input type="text" class="form-control" name="verifyCode" style="width: 184px" id="verifyCode"> </div>
<p style="text-align: right;color: red;position: absolute" id="info"></p>
<button id="loginButton" class="btn btn-primary">登陆 </button> </div>

View Code

依赖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()==''&amp;&amp;$("#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("提示:服务器出错");
                    }
                }
            });
        }

View Code

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 ;
    }

View Code

ps:主要逻辑就是把随机生成的验证码放到session域,当用户提交请求时,获取表单数据然后进行比对<(^-^)>

效果图

图片描述

图片描述

提供的代码尽量以参考为主,如有疑问,欢迎提出