Java Study Notes-sessions (24) and java Study Notes

Source: Internet
Author: User

Java Study Notes-sessions (24) and java Study Notes

1. Use cookies to display the user's last access time

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// page output response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); request. setCharacterEncoding ("UTF-8"); // gets the output object PrintWriter out = response. getWriter (); // get Cookie array object Cookie [] cookies = request. getCookies (); // defines a time String variable String date = null ;/ /Define a variable storage system's current Date current_date = new Date (); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss "); // determine if it is the first time you log on to if (cookies! = Null) {// directly loop for (Cookie cookie: cookies) {// obtain Cookie if ("lasttime ". equals (cookie. getName () {// obtain the last access time date = cookie. getValue (); break;} else {// obtain the system time date = format. format (current_date) ;}} else {// obtain the system time date = format. format (current_date);} // display time out. println (date); // write the access time to Cookie new_cookie = new Cookie ("lasttime", format. format (new Date (); new_cookie.setMaxAge (5*60); new_cookie.setPath ("/day08/showtime"); // send response. addCookie (new_cookie );}
Cookie details Session Technology

When we used the Cookie technology to store session information, we found that the data stored in cookies is limited, and the client browser needs to carry data each time, resulting in excessive network load. Therefore, if you need to store a relatively large amount of data, you can directly store the data on the server side, which can improve the data access speed.

HttpSession technology stores session data on the server to facilitate direct access by developers.

1 HttpSession Interface

This interface mainly defines a way to distinguish different users and obtain the user-related information of the Instance Storage of the object through the request object.

The object of this interface is created by the tomcat server to help developers. When the developer calls the request. getSession () method to obtain the object of this interface.

2. Common APIs

Get HttpSession object

HttpSession getSession () is directly returned. If no value is directly created, HttpSession getSession (boolean create) is returned. true is the same as above. If false is returned, no null is returned.

Operation data

Void setAttribute (String name, Object value) is used to set the attribute value of a specified name. Object getAttribute (String name) is used to obtain the attribute value of a specified name. Enumeration getAttributeNames () obtains the void removeAttribute (String name) of the Set iterator for all attribute names to delete the attribute of the specified name.

Additional methods

String getId () gets the Session ID value boolean isNew () determines whether the Session is a new long getCreationTime () gets the longlong getLastAccessedTime () of the Session Creation Time () obtain the time of the last Session access. The specified void invalidate () Session is invalid.

3. Reading and Writing of HttpSession

1. Write Session data

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// obtain the session object HttpSession session = request. getSession (); // place the data session. setAttribute ("name", "jack ");}

In the response, Set-Cookie: JSESSIONID = 8AA06CD311EC6A38805C73C93B8FCE4F; Path =/day08 is used to send the ID value of the HttpSession object to the browser as a Cookie for storage.

2. Read Session data

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// obtain the Session object HttpSession session = request. getSession (); // obtain the Session data String name = (String) session. getAttribute ("name"); // output information System. out. println (name );}

In the request message, use Cookie: JSESSIONID = 8AA06CD311EC6A38805C73C93B8FCE4F to carry the ID value of the HttpSession object. Then, the server finds the corresponding HttpSession object to obtain the value.

Summary:

At the underlying layer of HttpSession technology, the Cookie storage server needs to use the ID value of the HttpSession object created for each user, so that the value can be obtained later to obtain the median value of the specified object on the server.

3. Review the above Code

You can modify the code for getting sessiond from the servlet that obtains data as follows:

HttpSession session = request. getSession (false );

Currently, when the actual browser starts multiple windows in the same browser, the same Session object is automatically used. Once the validity period of a Session exceeds half an hour, the Session is automatically destroyed.

4. Other common methods

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// obtain the session object HttpSession session = request. getSession (); // call the common method System. out. println ("getId ():" + session. getId (); System. out. println ("getLastAccessedTime ():" + session. getLastAccessedTime (); System. out. println ("isNew ():" + session. isNew (); System. out. println ("getCreationTime ():" + session. getCreationTime ());}

Running result

getId(): F8A7BC23A0B403CE30A69F8B5F903D6AgetLastAccessedTime(): 1358385915203isNew(): truegetCreationTime(): 1358385915203

If session. invalidate (); is used in the above Code and the data is added to the session, the server reports an error.

java.lang.IllegalStateException: setAttribute: Session already invalidated

Summary:

Login Function Analysis 1. Get user data 2. Verify data 3. succeeded, store user login ID in Session

Logout Function Analysis 1. Clear the user identification information in the Session 2. Redirect to the login page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.