案例——利用Cookie实现自动登录
//login.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <html> <head> <title>用户登录</title> </head> <body> <form method="post" action="logincheck.jsp"> 用户名:<input type="text" size="10"name="username"><br/> 密 码:<input type="password" name="userpwd"/><br/> <input type="submit" value="登录"> </form> </body> </html>
//logincheck.jsp <%@ page pageEncoding="UTF-8"%> <html> <head> <title>登录处理</title> </head> <body> <% String un=request.getParameter("username"); if(un!=null) { Cookie c=new Cookie("username",un); c.setMaxAge(30*24*3600); response.addCookie(c); session.setAttribute("username",un); response.sendRedirect("main.jsp"); } %> </body> </html>
<%@ page pageEncoding="UTF-8"%> <html> <head> <title>主页面</title> </head> <body> <% String username=(String)session.getAttribute("username"); if(username==null) { Cookie[] cs=request.getCookies(); String v=null; if(cs!=null) { for(int i=0;i<cs.length;i++) { if(cs[i].getName().equals("username")) { v=cs[i].getValue(); } } } if(v!=null) { session.setAttribute("username", v); out.println(v+",您好"); } else { out.println("您还没注册,2秒后转到注册页面"); response.setHeader("Refresh","2;url=login.jsp"); } } else {out.print(username+",您好"); }%> </body> </html>