pp_crz_coder

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Cookie  ----->  browser

Session -----> server

When a client access to a server, there will be some data in this process, the server should save these data.

How to construct a cookie?

  Cookie cookie = new Cookie(String name, String value);

If you want to add the cookie to the browser, we should use:

  response.addCookie(Cookie cookie);

If you want to get all the cookies in the server, we should use:

  Cookie[] cookies = request.getCookies();

Cookie is stored in the browser's memory, when you close the browser, the cookie will dispear at the same time.

If you want to store the cookie for some time ( store the cookie in the disk ) , you can use the following method:

  cookie.setMaxAge(int time);

Specifies a path for the cookie to which the client should return the cookie:

  cookie.setPath(String url);

Delete cookie(the path should be identical, if you want to delete the cookie, i.e. cookie.setPath(String url) the url should be identical. ):

  cookie.setMaxAge(0);  delete the cookie immediately

  cookie.setMaxAge(-1);  delete the cookie when we close the browser

The shopping cart project!

The HttpSession:

  1. How to get the session object?

    request.getSession();

  The sesseion is a domain object:

    sesseion.setAttribute();

    session.getAttribute();

    session.removeAttribute();

The session principle:

  2. How to make sure the session is the only session.

    First, save the session id to the cookie, and when a request is sent, the id value will be passed to the server.

    The server will tell the id is exsited or not, if existed, get the session and use it, if not, the session id will be created.

How to destroy the session?

  1. shut down the server.

  2. session has its default time-out

    in the web.xml of tomcat, there is:

      <session-config>

        <session-timeout>30</session-timeout>

      <session-config>

  3. there is a method in HttpSession to invalidate the session:

    session.invalidate();

  4. set the time-out via HttpSession:

    session.setMaxInactiveInterval(int second);

 

Servlet's domain object:

  1. ServletContext: the whole application scope

  2. HttpSession: the session scope

  3. HttpServletRequest: the request scope

Three common method of domain object:

  Object getAttribute(String name);

  void setAttribute(String name, Object obj);

  void removeAttribute(String name);

Which domain object we should use?

  We should use the HttpServletRequest domain object as most as we can. The HttpServletRequest domain object's life circle is short, and its effeciency is high.

posted on 2017-07-27 16:50  ppcoder  阅读(105)  评论(0编辑  收藏  举报