Java in-depth exploration 06

Source: Internet
Author: User
Tags send cookies

get the resource file in Tomcat:

ServletContext (). Getrealpath (/web-inf/classes/db.properties);// Get the absolute path of the resource file in the server

ServletContext () getResourceAsStream () Gets the resource file and returns the input stream

ServletContext (). Getrealpath

Session Management

1. Definition: Managing session data generated during a browser and inter-server session

2. Domain objects: Implementing the sharing of data between resources

3. Session data

A) Cookies: session data is saved in the browser client

      1. Use process:

1.Cookie objects are created on the server by the new Cookie (Name,value,)

2. Send to client Respond.addcookie (Cookie) ( This implicitly sends a set-cookie response header Set-cookie:name=value)

3. browser gets this cookie will be saved the next time you access the server, you will be taken with cookie information (implicitly with a cookie: Name=value 's request header)

4. the server obtains the Cookie object that the browser sends request.getcookies ()

      1. Main methods

Construction: Cookie (String, value);

setting:setmaxage (int expiry)/ /Setting the effective time of the cookie

SetValue (String newvalue);// set a new Cookie value

SetPath (String path);// set a valid access path

Occurrence:addcookie (cookie);

Service Side Accept:request.getcookies ();

      1. Attention:

Cookies can only hold non-Chinese string types, save multiple cookies, and a browser can save A single cookie, Each site can only be stored - one, each Cookies Size Limit 4kb;

Setmaxage (int expiry): positive: The browser client hard disk time exists;

negative number: In browser memory, close the browser is not

0: Delete the same name Cookie Data

      1. Example: Saving a user's last access time
/*** Case-user last access time *@authorAPPle **/ Public classHistservletextendsHttpServlet {/** * */Private Static Final LongSerialversionuid = 1L;  Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8"); //Get current TimeSimpleDateFormat Format=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); String Curtime= Format.format (NewDate ()); //Obtaining Cookiescookie[] Cookies=request.getcookies (); String Lasttime=NULL;if(cookies!=NULL){ for(Cookie cookie:cookies) {if(Cookie.getname (). Equals ("Lasttime")){//There are lasttime cookies that have been visited for the nth timeLasttime= Cookie.getvalue ();//time of last visit//Nth Visit//1. Display the last display time to the browserresponse.getwriter (). Write ("Welcome back, the last time you visited:" +lasttime+ ", the current time is:" +curtime);//2. Update CookiesCookie.setvalue (curtime); Cookie.setmaxage (1*30*24*60*60);//3. Send the updated cookie to the browserResponse.addcookie (cookie); Break;}}} /*** First visit (no cookie or cookie, but no cookie named Lasttime)*/if(cookies==NULL|| lasttime==NULL){//1. Show current time to browserresponse.getwriter (). Write ("You are the first to visit this website, the current time is:" +curtime);//2. Create a Cookie objectCookie Cookie=NewCookie ("Lasttime"), Curtime); Cookie.setmaxage (1*30*24*60*60);//save one months//3. Send cookies to the browser to saveResponse.addcookie (cookie);}} }
View Code

b) Session: Sessions data is stored on the server

    1. Reason for the occurrence:

A) Cookies have their own shortcomings, the maximum 4kb, only non-Chinese restrictions,theSession can solve the problem, can save objects, any type of data

b) The server can identify different browsers, which domain the data is stored in must be from that domain or get the object

    1. Use process:

Different browser request objects get different domain objects

HttpSession session=request.getsession (); you just have to parse his process.

A) The first time a browser creates a session domain object, the server assigns a Jsessionid object to the session object that uniquely identifies the session object that - "

b) Send this jsessionid to client Respond.addcookie ("Jsessionid", SessionID)

c) After the browser sends the request to the server with the Jsessionid request header from the server to find the supplied session Object -"

D) find the object and repeat A as soon as it's not found.

    1. Main methods

A) Create:request.getsession ([true]);

b) set:setmaxinactiveinterval (int interval)// Set save time

Invalidate ();// Destroy this session Object

GetId ();// Get the Unique identifier of this Session jsessionid

    1. Attention:

A) destruction time setting: 30min,setmaxinactiveinterval (int interval) by default; set the time; the global setting destruction time can be Web. XML in the configuration

<!-- Modify session Global Effective Time : minutes --

<session-config>

<session-timeout>1</session-timeout>

</session-config>

; Manual Destruction:invalidate ()

b) How to avoid the problem that the browser's Jsessionid cookie is lost as the browser shuts down

manually set the browser's Cookie Time

Cookie Cookie=new Cookie ();

Cookie.setmaxage (60*60);

Response.addcookie (cookie);

    1. Example:
//1. Get the Session objectHttpSession Session= Request.getsession (false); if(session==NULL) {System.out.println ("No corresponding Sessino object found");return;} /*** Get Session number*/System.out.println ("Id=" +Session.getid ()); //2. Remove the dataString name= (String) session.getattribute ("name"); System.out.println ("Name=" +name);
View Code

Java in-depth exploration

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.