Login.jsp
<form name = "f1" method="get" action="servlet/LoginServlet"> <table> <tr> <td>Username:</td> <td><input type="text" name="username" value="${un}"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name = "password" value="${pw}"></td> </tr> <tr> <td>AutoLogin:</td> <td><input type="checkbox" name = "auto" value = "1"></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Login"> </td> </tr> </table> </form>
PrepareLogin
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cs = request.getCookies(); if(cs!=null && cs.length>0){ for(int i = 0 ; i < cs.length ; i++){ Cookie c = cs[i]; System.out.println(cs.length); System.out.println(i+"--"+cs[i].getName()); if(c.getName().equals("username")){ String value = c.getValue(); request.setAttribute("un", value); System.out.println(value); } if(c.getName().equals("password")){ String value = c.getValue() ; request.setAttribute("pw", value); //将值传递给jsp页面 System.out.println(value); } } } request.getRequestDispatcher("/login.jsp").forward(request, response); }
保存Cookie protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String auto = request.getParameter("auto"); String username = request.getParameter("username"); String password = request.getParameter("password"); if(auto != null && auto.equals("1")){ Cookie u = new Cookie("username", username); Cookie p = new Cookie("password",password); u.setMaxAge(60*60); p.setMaxAge(60*60); response.addCookie(u); response.addCookie(p); } PrintWriter w = response.getWriter(); w.println("<html>"+ "Hello"+ "</html>" ); w.flush(); w.close(); }
时间: 2024-10-14 06:54:37