Cookie 和 Session

 

 

 

 

 

免用户名登录的实现细节和原理:

 

 面用户名密码登录实现:

public class LoginServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        if("123456".equals(password) && "wzg168".equals(username)) {
            Cookie cookie = new Cookie("username",username);
            cookie.setMaxAge(60*60*24*7);
            resp.addCookie(cookie);
            req.getRequestDispatcher("index.jsp").forward(req, resp);
            
        }else {
            System.out.println("登录失败");
        }
        
    }

}

login.jsp

    <form action="http://localhost:8080/cookieDemo/loginServlet" method="get">
    用户名:<input type="text" name="username" value="${cookie.username.value}"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
    </form>

 

Session:

 

 

如何创建Session和获取(id号,是否为新)

如何创建和获取Session。它们的API是一样的:request.getSession()

  第一次调用是:创建Session会话

  之后调用都是:获取前面创建好的Session的会话

 

 isNew():判断到底是不是刚创建出来的(新的)Session

   true表示刚创建,false表示获取之前创建

 每个会话都有一个身份号码,也就是ID值。而且这个ID是唯一的。

  getId()得到Session会话的ID值。

 

Session生命周期控制:

  setMaxInactiveInterval(int interval) 设置Session的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。

 get setMaxInactiveInterval() 获取Session的超时时间

 

 

修改个别 Session的超时时长则只需要调用  setMaxInactiveInterval(int interval) 设置即可。

posted @ 2021-11-15 22:15  donkey8  阅读(17)  评论(0)    收藏  举报