cookie的使用
效果截图:
再次登录:
servlet代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset =utf-8" ); PrintWriter out = response.getWriter();//创建输出流 String UserName = request.getParameter("username");//获取输入的信息 String Pswd = request.getParameter("password"); String getNull = request.getParameter("checkbox"); Cookie[] cookies = request.getCookies(); if(cookies!=null) { for (Cookie cookie : cookies) {//遍历cookie String cookname = cookie.getName(); if(cookname.equals("UserName")) { UserName = cookie.getValue(); } if(cookname.equals("Pswd")) { Pswd = cookie.getValue(); } getNull="0"; } } if(UserName.equals("tom")&&Pswd.equals("123")&&getNull.equals("1"))//判断是否正确和是否勾选自动登陆 { Cookie cookie= new Cookie("UserName", UserName);//建立cookie Cookie cookie2 = new Cookie("Pswd",Pswd); cookie.setMaxAge(2592000);//设置cookie的生存时间 cookie2.setMaxAge(2592000); response.addCookie(cookie); response.addCookie(cookie2);//将建立的cookie存入 out.println("<p>欢迎"+UserName+",你已登录成功!</P>"); } else if(UserName.equals("tom")&&Pswd.equals("123")&&getNull.equals("0")){ out.println("<p>欢迎"+UserName+",你已登录成功!</P>"); out.println("<p>你已记住密码</p>"); } else if(UserName.equals("tom")&&Pswd.equals("123")){ out.println("<p>欢迎"+UserName+",你已登录成功!</P>"); } else { out.println("用户名或者密码错误"); } }
Filter代码:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here // pass the request along the filter chain // 将请求转换成HttpServletRequest请求 HttpServletRequest httpRequest=(HttpServletRequest)request; // 将响应转换成HttpServletResponse响应 HttpServletResponse httpResponse = (HttpServletResponse)response; //截取用户的请求地址 String from =httpRequest.getServletPath(); if(from.equals("/index.html")) { //获取本站在客户端上保留的所有的cookie Cookie[] cookies=httpRequest.getCookies(); if(cookies!=null) { //遍历cookie数组 httpResponse.sendRedirect("Login"); } // 放行请求 chain.doFilter(request, response); } else { chain.doFilter(request, response); } }