May 9, 2018 java-servlet02

Source: Internet
Author: User
Tags session id

  1. The session object is used to record the access state of each client within the scope of a conversation, so that it keeps track of the state of each client's operations, the information stored in the session, and the valid data for those sessions when the browser makes subsequent requests.
  2. You can use the Session object (the JSP's built-in object) directly in the JSP page, or you can return to the session object via Pagecontext.getsession () or request.getsession.
  3. Session can save the user's information and implement functions such as shopping cart.
  4. The HTTP protocol is a stateless protocol, the client requests the request to the server, and then the server returns the response response, the connection is closed, the server does not save the connection information, so on the next connection, the server has no previous connection information, You cannot determine the same customer information for this connection and the last connection, so you must use the session to record information about the connection.
  5. From the client to open the browser to connect to the server, the client closes the browser and leaves the server, calling to do a session. When a client accesses a server, it is possible to repeatedly connect to several pages on the server, repeatedly refresh a page, or continuously submit information to a page, etc., the server should know that this is the same customer by some means, then the session object is required.
  6. The session works as follows:
  7. 1. When the customer first accesses a page of the server, the server assigns a session object to the user, specifying a unique ID for the session and sending the ID to the client and writing to the cookie. So that the client and the server session to establish a one by one corresponding relationship;
  8. 2, when the client continues to access other resources on the server side, the server no longer assigns the client a new session object until the client browser closes, times out, or calls the session's invalidate () method to invalidate it, and the client and server session ends.
  9. 3. When the customer re-opens the browser to visit the site, the server will re-assign the client a Session object and reassign the SessionID.
  10. Session objects are primarily used for attribute manipulation and session management, and are commonly used in the following ways:
  11. 1,public void SetAttribute (String name,string value) sets the value of the property of the specified name and adds it to the session scope, changing the value of the property if it exists within the session scope.
  12. 2, publicObject getattribute (String name) Gets the value of the property of the specified name within the session scope, returns a value of type Object, or null if the property does not exist .
  13. 3,public void RemoveAttribute (String name), removes the session property of the specified name, and if the property does not exist, an exception occurs.
  14. 4,public Void invalidate (), so that the session expires.  The current session can be invalidated immediately, and all objects stored in the original session are no longer accessible.
  15. 5, publicString getId (), gets the current session ID.  Each session has a unique identifier on the server side the only data that the Sessionid,session object sends to the browser is SessionID, which is generally stored in a cookie.
  16. 6,public void setmaxinactiveinterval (int interval) sets the maximum duration of the session, in seconds, and negative numbers indicate that the session will never expire.
  17. 7,public int getmaxinactiveinterval (), gets the maximum duration of the session.
  18. 8. The GetCreationTime () and Getlastaccessedtime () methods of the Session object can be used to get the time of creation and last access, but the return value is milliseconds, which is generally required to get the specific date and time using the following conversion.
  19. Date CreationTime = new Date (Session.getcreationtime ());
  20. Date Accessedtime = new Date (Session.getlastaccessedtime ());
  21. <%@ Page Language="Java"Import="java.util.*"ContentType="TEXT/HTML;CHARSET=GBK"%>  <%  StringPath=Request.getcontextpath (); StringBasePath=Request.getscheme ()+"://"+Request.getservername ()+":"+Request.getserverport ()+Path+"/"; %>  <!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en">  <HTML>    <Head>      <Basehref= "<%=basePath%>">           <title>Session Object method</title>        <Metahttp-equiv= "Pragma"content= "No-cache">   <Metahttp-equiv= "Cache-control"content= "No-cache">   <Metahttp-equiv= "Expires"content= "0">      <Metahttp-equiv= "keywords"content= "Keyword1,keyword2,keyword3">   <Metahttp-equiv= "description"content= "This is my page">   <!--<link rel= "stylesheet" type= "Text/css " href= "Styles.css" > -    </Head>       <Body>      <b>Session ID:<%=Session.getid ()%> <BR>whether to new session:<%=session.isnew ()%><BR>set and Get Property object: User name =<%Session.setattribute ("User name","Bing"); %>      <%=Session.getattribute ("User name") %><BR>      <%      DateCreationTime= New Date(Session.getcreationtime ()); DateAccessedtime= New Date(Session.getlastaccessedtime ()); %>Session creation Time:<%=CreationTime%><BR>Last access time:<%=Accessedtime%><BR>session Duration (s):<%=Session.getmaxinactiveinterval ()%><BR>       <%Session.setmaxinactiveinterval ( A); %>modified session Duration (s):<%=Session.getmaxinactiveinterval ()%><BR>       <%session.invalidate ();%>       </b>    </Body>  </HTML>  
  22. When the browser accesses the server, the server sends some data to the browser in the form of a Set-cookie message header. The browser will save the data. When the browser accesses the server again, the data is sent to the server in the form of a cookie message header.

    2. Create a cookie

    New Cookie (String name,string value); Response.addcookie (cookie);

    The name of the cookie cannot be duplicated, similar to the map collection, and is substituted when there is a duplicate name.

    3. Query cookies

    // If there is no cookie, NULL is returned. cookie[] cookies == = Cookie.getvalue ();

    4. The encoding problem when the cookie is saved

    The value of the cookie just can be an ASCII character, and if it is Chinese, it needs to be converted into ASCII characters. This conversion can be done using the Urlencoder.encode () method and the Urldecoder.decode () method.

    5. Save time for Cookies

    Cookie.setmaxage (int seconds);//Unit is seconds
    ? Seconds > 0
    The browser saves the cookie as a file on the hard disk. After a specified time has passed, the file is deleted.
    ? Seconds < 0
    Default, the browser stores the cookie in memory. Just will not be deleted until the browser is closed.
    ? seconds = 0
    Delete the Cookie now

    6. Delete Cookies

    For example, delete a cookie with the name "username".
    Cookie C = new Cookie ("username", "");
    C.setmaxage (0);
    Cookie.setpath (Request.getcontextpath ());//path
    Response.addcookie (c);

    7. Restrictions on Cookies

    ? Cookies can prohibit
    ? The size of the cookie is limited (around 4k)
    ? There is also a limit on the number of cookies (the browser can store about 300)
    ? The value of the cookie just can be a string, consider the encoding problem.
    ? Cookies are not secure

    8. Path Problem of cookies

    When a browser sends a request to an address on the server, it compares the path of the cookie to the path of the access (address) to match, and the just has a matching cookie before it is sent.
    The path to the cookie can be set by using the Cookie.setpath (String path) method. If there is no setting, there is a default path, and the default path is the path of the component that generated the cookie.
    For example:/appname/addcookie saves a cookie, the path to the cookie is/appname/addcookie.
    Rules:
    The path to the cookie must be the upper directory of the path to be accessed, and the browser will not send the cookie to the server until the path is equal. You can typically set SetPath ("/appname"), which means that all addresses that are accessed under the app are sent

  23. How does the server identify a particular customer? This time the cookie is on the scene. Each time the HTTP request is sent, the client sends the appropriate cookie information to the server. In fact, most of the applications are using cookies to achieve session tracking, the first time the session is created, the server will be in the HTTP protocol to tell the client, you need to record a session ID in the cookie, each request to send this session ID to the servers , I know who you are, note that the first request, there is no Cookie in the request header, the response header will be set-cookie. On the first request, the set-cookie:session in the response header takes advantage of the cookie implementation mechanism: Someone asked, what if the client's browser disables cookies? In this case, a technique called URL rewriting is used for session tracking, that is, each HTTP interaction, after which a parameter such as Jsessionid is appended to the URL, and the server identifies the user accordingly.
    <a href= "<%=response.encodeurl (" getsession.jsp ")%>" > Jump to the page that gets the session </a>
    Cookies can also be used in a number of user-friendly scenarios, imagine that you have landed a website, the next time you log in and do not want to enter the account again, how to do? This information can be written into the cookie, visit the site, the Site page script can read this information, automatically help you to fill out the user name, to facilitate the user. This is also the origin of the name of the cookie, to the user a little sweetness. Session is inserver-side SaveA data structure that can be used to keep track of a user's state, which is stored in a cluster, database, or file;
    Cookie isClient SaveA mechanism of user information, used to record some information of the user, is also a way to implement the session. Cookies Sent:
    <%    Cookie c = new Cookie ("name", "Gareen");//Key value pair    c.setmaxage (60*60*24);//valid for 24 hours, local persistence    C.setpath (" 127.0.0.1 ");//path represents the hostname of the server, and only the browser accesses the server through this hostname, the cookie is submitted to the service side    Response.addcookie (c);//Send generated cookie%> <a href= "getcookie.jsp" > Jump to the page to get cookies </a>

    Note the problem with path:

    Path represents the directory where the cookie resides. "/" means the root directory, and all pages have access to the cookie under the root directory. If the path of the cookie is test, then only the pages and code of the test directory or subdirectories under test will get this cookie.

    such as Http://localhost:8080/Web02/test

    The path value of the URL is set directly to the cookie when the path value is end with "/"

    When the path value of the URL does not end with "/", see if there is a "/" in the path

    Example: Http://localhost:8080/Web02/test/testServlet

    If there is a "/", simply intercept the last "/" and set the path value of the cookie.

    If there is no "/", set the path of the cookie to "/".

    Cookie Read

    cookie[] cookies = request.getcookies ();   if (cookie = null) for     (int i=0;i<cookies.length;i++) {        response.getwriter (). Print (Cookies[i].getname () + ":" +cookies[i].getvalue ());     }

    Cookie deletion

    Cookie C = new Cookie ("name", "Peter"); C.setmaxage (24*60*60);  C.setpath ("/"); Response.addcookie (c); Cookie cookie = new Cookie ("username", "Peter");//New Cookiecookie.setmaxage (0);                           The set life cycle is 0, indicating that Response.addcookie (cookie) will be deleted;     

May 9, 2018 java-servlet02

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.