Java Learning notes-using HttpSession to implement QQ Access Records (31)

Source: Internet
Author: User
Tags close page server memory

1. Writing the QQ Space data Class (Qqs.java)

 Public classQqs {Private StaticLinkedhashmap<integer, string> Qqs =NewLinkedhashmap<integer, string>(); Static{qqs.put (10001,"Zhang San"); Qqs.put (10002,"John Doe"); Qqs.put (10003,"Harry"); Qqs.put (10004,"Zhao Liu"); Qqs.put (10005,"Tianqi"); Qqs.put (10006,"Coke Eight"); Qqs.put (10007,"Hou Jiu"); Qqs.put (10008,"Willow 10"); Qqs.put (10009,"Little Two"); }     Public StaticLinkedhashmap<integer, string>Getqqs () {returnQqs; }}

2. Write a real-world QQ data and Browsing history page (Listservlet.java)

 Public voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {//Get Session ObjectHttpSession session =request.getsession (); //set up Chinese dataResponse.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); //Get output streamPrintWriter out=Response.getwriter (); //Get Qqs DataLinkedhashmap<integer, string> Qqs =Qqs.getqqs (); Set<map.entry<integer, string>>Set=Qqs.entryset (); Iterator<map.entry<integer, string>> it =Set. iterator (); //Output page Structure         out. println ("");  out. println ("");  out. println ("");  out. println (""); //hyperlinks for circular output QQ space         while(It.hasnext ()) {Map.entry<integer, string> entry =It.next (); Integer Num=Entry.getkey (); String name=Entry.getvalue ();  out. println ("<a href=\ "/day08/store?num="+num+"\ ">"+name+"</a>"); }        //record information for output browsing         out. println ("");  out. println ("");  out. println (""); //get access to record dataString history = (string) Session.getattribute (" History"); if(History = =NULL){             out. println ("<font color=\ "red\" > Sorry, no access record at this time ...</font>"); }Else{            //looping through user-accessed record datastring[] Nums = History.split (",");  for(String num:nums) {string name= Qqs.getqqs ().Get(Integer.parseint (num));  out. println (name+" ,"); }        }        //Close page Structure         out. println ("</body>"); }

3. Write a store to browse the QQ Space page (Storeqqservlet.java)

 Public voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {//Get Session ObjectHttpSession session = Request.getsession (false); //GET Request ParametersString num = Request.getparameter ("Num"); //get the data in sessionString history = (string) Session.getattribute (" History"); //Judging Data        if(History = =NULL){            //first time VisitSession.setattribute (" History", num);//history=10001}Else{            //Access multiple timesSession.setattribute (" History", history+","+num); //set the number of NUM and the order in which it is displayedstring[] Qqs = History.split (","); //converts an array to a collection of convenient operationslist<string> list =arrays.aslist (QQS); //Convert list to LinkedList easy to manipulate dataLinkedlist<string> linked_list =NewLinkedlist<string>();            Linked_list.addall (list); //determine the number of QQ occurrences            if(Qqs.length <3 ){                if(Linked_list.contains (num)) {//history=10002,1003//If you includelinked_list.remove (num);                Linked_list.addfirst (num); }Else{//history=1004,10002,1003//does not containLinked_list.addfirst (num); }            }Else{//>= 3                if(Linked_list.contains (num)) {//history=10002,10003,10004 10004//If you includelinked_list.remove (num);                Linked_list.addfirst (num); }Else{//history= 10005, 10002,10003//does not containLinked_list.removelast ();                Linked_list.addfirst (num); }            }            //A good number of times, a good sequence of access records linked_listStringBuffer SB =NewStringBuffer ();  for(String new_num:linked_list) {sb.append (New_num+","); } String new_history=sb.tostring (); Session.setattribute (" History", new_history); }        //REDIRECT to QQ list pageResponse.sendredirect ("/day08/list"); }

The above code stores the user's browsing history in the session object, but the object is in server memory and has a valid time limit, and if the time is up, the session will be destroyed.

The default time is half an hour (30 minutes).

4 Configuring the session's effective time

In Web. XML for each site, you can configure the time that the session object created by the site is valid. Note that the configured time unit is minutes.

THREAD.SLESSP (millisecond units), cookie.setmaxage (seconds), session (minutes)

  <session-config>    <session-timeout>2</session-timeout>        units are minutes   </session-config>

5 Disabling of cookies

Cookies can use the client to store session data.

HttpSession can use cookies to store sessionid information.

In fact, in the browser settings can be denied the website sent back cookie information.

Accessing the above case at this point causes the null pointer exception to appear. If you need to fix the site, you must use urlrewriting technology.

Urlrewritting

Analyze the reasons for the above problems:

The server has created the session object, but because the browser prohibits the receipt of the cookie, the server cannot send the ID value of the created session to the browser for storage in the Set-cookie response header mode. Then in the second visit will not slack SessionID, so can not find the session.

Common methods

String encoderedirecturl (string url)     ? Adds SessionID information to the specified redirect path after the string encodeurl (string url)            ? Add SessionID information to an ordinary URL address

Principles of Implementation:

"Re-encode all URL addresses in the page using the method above"

1 Modify the above procedure

1 Listservlet.java

" /day08/store?num= "+num;   = Response.encodeurl (path);   out. println ("<a href= '"+path+">" + name+"</a>");

2. Storeqqservlet.java

" /day08/list "  = response.encoderedirecturl (path); response.sendredirect (path);

Java Learning notes-using HttpSession to implement QQ Access Records (31)

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.