需求说明:
完成用户登录功能,如果用户勾选“记住用户” ,则下次访问登录页面自动填充用户名密码
完成注册功能,并实现验证码功能
记住用户
如果用户勾选“记住用户” ,则下次访问登陆页面自动填充用户名密码
如何自动填充用户名和密码?
将用户名和密码写入Cookie中,并且持久化存储Cookie ,下次访问浏览器会自动携带Cookie
在页面获取Cookie数据后,设置到用户名和密码框中
${cookie.key.value} // key指存储在cookie中的键名称
何时写Cookie?
登录成功
用户勾选记住用户复选框
核心代码:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 获取用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); //获取复选框数据 String remember = request.getParameter("remember"); //2. 调用service查询 User user = service.login(username, password); //3. 判断 if(user != null){ //登录成功,跳转到查询所有的BrandServlet //判断用户是否勾选记住我 if("1".equals(remember)){ //勾选了,发送Cookie //1. 创建Cookie对象 Cookie c_username = new Cookie("username",username); Cookie c_password = new Cookie("password",password); // 设置Cookie的存活时间 c_username.setMaxAge( 60 * 60 * 24 * 7); c_password.setMaxAge( 60 * 60 * 24 * 7); //2. 发送 response.addCookie(c_username); response.addCookie(c_password); } //将登陆成功后的user对象,存储到session HttpSession session = request.getSession(); session.setAttribute("user",user); String contextPath = request.getContextPath(); response.sendRedirect(contextPath+"/selectAllServlet"); }else { // 登录失败, // 存储错误信息到request request.setAttribute("login_msg","用户名或密码错误"); // 跳转到login.jsp request.getRequestDispatcher("/login.jsp").forward(request,response); } }
jsp页面代码
<div id="loginDiv" style="height: 350px"> <form action="/login/loginServlet" method="post" id="form"> <h1 id="loginMsg">LOGIN IN</h1> <div id="errorMsg">${login_msg} ${register_msg}</div> <p>Username:<input id="username" name="username" value="${cookie.username.value}" type="text"></p> <p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password"></p> <p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p> <div id="subDiv"> <input type="submit" class="button" value="login up"> <input type="reset" class="button" value="reset"> <a href="register.jsp">没有账号?</a> </div> </form> </div>
标签:username,用户名,登录,request,用户,案例,Cookie,注册,password From: https://www.cnblogs.com/popopopopo/p/17080058.html