Layui + Servlet 实现验证登入

 准备前端页面 Login.jsp 

- Layui 下载地址 Layui

  • 引入 css 
  • 引入 js 

  • 放入 IDEA -> webapp -> static -> plugins 下,引入
    <link rel="stylesheet" type="text/css" href="/static/plugins/layui2.7.6/css/layui.css" />
    <script type="text/javascript" src = "/static/plugins/layui2.7.6/layui.js"></script>
  • 其它 html
<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md4 layui-col-md-offset4">

            <div class="loginForm">
                <span ${message == null ? "style='dispaly:none'" : "style='color:red'"}>${message}</span>
                <h2 style="text-align: center">QQ系统</h2>
                <form class="layui-form" lay-filter="formData"  method="post" action="/login">

                    <div class="layui-form-item">
                        <label>用户名:</label>
                        <div class="layui-form-block">
                            <input type="text" name="username" required lay-verify="required|username"
                                   placeholder="请输入用户名" class="layui-input" value="${username}">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label>密码:</label>
                        <div class="layui-form-block">
                            <input type="password" name="password" required lay-verify="required|password"
                                   placeholder="请输入密码" class="layui-input" value="${password}">
                        </div>
                    </div>

                    <!-- 验证码-->
                    <div class="layui-form-item">
                        <label>验证码:</label>
                        <div class="layui-form-block">
                            <input style="width: 100px;display: inline" type="text" name="vcode" required lay-verify="required|vcode"
                                   placeholder="请输入验证码" class="layui-input">
                            <img src="/code" alt="验证码" title="看不清,换一张" onclick="this.src='/code?'+Math.random()" />
                        </div>

                    </div>

                    <div class="layui-form-item">
                        <div class="layui-form-block">
                            <input type="checkbox" name="isRemember" lay-skin="primary" title="记住我" ${isRemember == true ? "checked" : ""}>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-form-block">
                            <button class="layui-btn" lay-submit lay-filter="loginForm" id="submitBtn">登录</button>
                            <a class="layui-btn layui-btn-normal" href="/register">注册</a>
                        </div>
                    </div>
                </form>
            </div>

        </div>
    </div>
</div>
  • Layui 的 js 部分
    <script>
        layui.use(['form','jquery'],function () {
    
            var form = layui.form;
            var $ = layui.jquery;
    
            // 点击事件
            $('#submitBtn').on('click',function (data) {
    
                     form.verify({
                         username: function (value) {
                             if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                                 return '用户名不能有特殊字符';
                             }
                             if(/(^\_)|(\__)|(\_+$)/.test(value)){
                                 return '用户名首尾不能出现下划线\'_\'';
                             }
                             if(/^\d+\d+\d$/.test(value)){
                                 return '用户名不能全为数字';
                             }
                         },
                         password: [
                             /^[\S]{6,12}$/,
                             '密码必须6到12位,且不能出现空格'
                         ],
                         vcode: function (value) {
                            if(!new RegExp("^[a-z0-9]{4}$").test(value)) {
                                return '验证码由小写与数组组成,长度为4'
                            }
                         }
                     })
                // });
                 // 返回 true 可以提交表单
                return true;
            });
        });
    </script>

     LoginController.java

@WebServlet("/login")
public class LoginController extends HttpServlet {

    /**
     * 在 web.xml 里面需要配置一个 welcome-file-list 地址为 login -> 启动项目时执行这个 doGet方法
     * @param req   an {@link HttpServletRequest} object that
     *                  contains the request the client has made
     *                  of the servlet
     *
     * @param resp  an {@link HttpServletResponse} object that
     *                  contains the response the servlet sends
     *                  to the client
     *
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 Cookie
        String cookie = CookieUtils.getCookieValue(req, "admin");

        if (cookie != null && !cookie.equals("")) {
            // xxx:yyy

            String[] split = cookie.split(":");
            // 把账号与密码 入域
            req.setAttribute("username",split[0]);
            req.setAttribute("password",split[1]);
            // 给复选框一个选中的状态
            req.setAttribute("isRemember",true);
        }
        // 转发到页面
        req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req,resp);
    }

    private AdminService adminService = new AdminServiceImpl();

    /**
     * 提交登入页面时请求 这个 doPost 方法
     * @param req   an {@link HttpServletRequest} object that
     *                  contains the request the client has made
     *                  of the servlet
     *
     * @param resp  an {@link HttpServletResponse} object that
     *                  contains the response the servlet sends
     *                  to the client
     *
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取登入的账号
        String username = req.getParameter("username");
        // 获取登入的密码
        String password = req.getParameter("password");

        /*
         获取记住我的状态
            如果没有选择记住我 就删除 Cookie
            如果选择了记住我 需要保存(账号和密码正确的情况下保存) Cookie
         */

        String isRemember = req.getParameter("isRemember");
        // 如果没有记住我就是 true, 记住我了就是 false
        boolean flag = isRemember == null ? true : false;

        // 没有选中记住我
        if (flag) {
            // 删除Cookie, 保存 Cookie 的名字 admin
            CookieUtils.deleteCookie(req,resp,"admin");
        }

        // 从后台获取生产的验证码
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        // 从页面获取验证码
        String vcode = req.getParameter("vcode");
        // 校验验证码不考虑大小写
        if (code.equalsIgnoreCase(vcode)) {
            Admin admin = adminService.login(username, password);
            // 登入成功
            if (admin != null) {
                    // 记住我
                    if (!flag) {
                        // 记住Cookie , 保存 7 天
                        CookieUtils.setCookie(req,resp,"admin",String.format("%s:%s",username,password),60*60*24*7);
                    }
                    // 把对象存入 session 域
                    session.setAttribute("admin",admin);
                    // 去首页
                    req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req,resp);
            }

            // 登入失败
            else {
                // 账号或密码错误 , 去登入页
                session.setAttribute("message","账号或密码错误");
                resp.sendRedirect("/login");
            }
        }
        else {
            // 验证码错误 , 去登入页
            session.setAttribute("message","验证码错误");
            resp.sendRedirect("/login");
        }
    }
}

AdminServiceImpl.java 

public class AdminServiceImpl implements AdminService {
    private AdminDao adminDao = new AdminDaoImpl();
    @Override
    public Admin login(String loginName, String loginPwd) {
        Admin admin = adminDao.findByName(loginName);
        if (null != admin) {
            // 登入的密码加密
            loginPwd =  MD5Utils.getMD5(loginPwd);
            // 把查询的密码与登入的密码做比较
            String pwd = admin.getLoginPwd();
            if (pwd.equals(loginPwd)) {
                return admin;
            }
        }
        return null;
    }
}

 AdminDaoImpl.java

public class AdminDaoImpl implements AdminDao {
    Connection conn = JDBCUtils.getConnection();
    @Override
    public Admin findByName(String loginName) {
        String sql = "select login_id,login_pwd,id,fileName from admin where login_id = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,loginName);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                Admin admin = new Admin();
                admin.setLoginId(rs.getString("login_id"));
                admin.setLoginPwd(rs.getString("login_pwd"));
                admin.setId(rs.getInt("id"));
                admin.setFileName(rs.getString("fileName"));
                return  admin;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}

 MD5Utils.java
 

public class MD5Utils {
    public static String getMD5(String value) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            // // 把数据 转换
            md5.update(value.getBytes());
            // 获取转换后的数据 md5.digest()
            // 获取转换后的数据 md5.digest()
            return new BigInteger(1,md5.digest()).toString(16);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

CookieUtils.java 

public class CookieUtils {
    /**
     * 得到Cookie的值, 不编码
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, false);
    }

    /**
     * 得到Cookie的值,
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    if (isDecoder) {
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookieList[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
          //  logger.error("Cookie Decode Error.", e);
        }
        return retValue;
    }

    /**
     * 得到Cookie的值,
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
           // logger.error("Cookie Decode Error.", e);
        }
        return retValue;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) {
        setCookie(request, response, cookieName, cookieValue, -1);
    }

    /**
     * 设置Cookie的值 在指定时间内生效,但不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) {
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
    }

    /**
     * 设置Cookie的值 不设置生效时间,但编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
    }

    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        doSetCookie(request, response, cookieName, "", -1, false);
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     *
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request)// 设置域名的cookie
                cookie.setDomain(getDomainName(request));
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
           // logger.error("Cookie Encode Error.", e);
        }
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     *
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encodeString);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request)// 设置域名的cookie
                cookie.setDomain(getDomainName(request));
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
           // logger.error("Cookie Encode Error.", e);
        }
    }

    /**
     * 得到cookie的域名
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;

        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }

        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }
}

验证码 

  • 导入验证码的依赖
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.7</version>
</dependency>
  • 后台代码
  • @WebServlet("/code")
    public class ValidateCode extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 创建一个大小为 120 * 40 的验证码
            LineCaptcha lc = CaptchaUtil.createLineCaptcha(120, 40, 4, 20);
            // 获得生产的验证码
            String code = lc.getCode();
            // 将生产的验证码存入 session域(存储数据)
            req.getSession().setAttribute("code",code);
            // 输出验证码
            lc.write(resp.getOutputStream());
        }
    }

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值