[Reprint] Methods for manipulating session variables in JSP through servlet in Java

Source: Internet
Author: User

 

Use servlet to control sessions

Session status maintenance is a problem that must be faced when developing Web applications. There are multiple ways to solve this problem, such as using cookies and hidden form fields, or directly add the status information to the URL medium, and the servlet itself provides an httpsession interface to support session State maintenance. Here we mainly introduce session state management based on this interface.

Session was invented to address the limitations of the HTTP protocol. Note how the HTTP protocol works-the user sends a request and the server responds. The connection between the client and the server is discrete and discontinuous. HTTP does not support server tracking of user requests. After the server responds to the user's request, the server cannot continue to connect to the browser. From the server perspective, each request is independent. Therefore, HTTP is considered as a stateless protocol. When a user switches between multiple homepages, the server cannot know his/her identity. The emergence of session is to make up for this limitation. With session, you can save the information of a user when switching between multiple home pages. This makes it much easier to do a lot of things that were never done before.

Each visitor obtains a session from the time the visitor arrives at a specific homepage to the time when the visitor leaves.
Java Servlet defines an httpsession interface to implement the session function. The process of using session in servlet is as follows:
  
(1) Use the getsession method of httpservletrequest to obtain the existing session. If no session is defined, a new session is created. You can also use the getsession method (true)

(2) write the session variable. You can use httpsession. setattribute (name, value) to store an information in the session. You can also use httpsession. putvalue (name, value), but this method is outdated.

(3) read the session variable. You can use httpsession. getattribute (name) to read a variable value in the session. If name is an unspecified variable, null is returned. Note that the variable type read from getattribute is object and mandatory type conversion is required. For example:
String uid = (string) Session. getattribute ("uid ");
You can also use httpsession. getvalue (name), but this method is outdated.

(4) Close the session. After the session is used up, you can use session. invalidate () to close the session. However, this is not strictly required. Because the servlet engine automatically closes the seesion after a period of time.

The following is a simple example of session usage.
// Sessionexample. Java
Import java. Io .*;
Import java. util .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
// Import necessary software packages
Public class sessionexample extends httpservlet
{
Public void doget (httpservletrequest request, httpservletresponse response)
Throws ioexception, servletexception // implement the doget Method
{
Response. setcontenttype ("text/html"); // you can specify the HTTP header.
Printwriter out = response. getwriter (); // get the output writer
Httpsession session = request. getsession (true );
// Obtain the session object

// Print the HTML Tag
Out. println ("");
Out. println ("");
Out. println ("");
Out. println ("");
Out. println ("");

Date created = new date (session. getcreationtime ());
// Obtain the time when the session object was created
Date accessed = new date (session. getlastaccessedtime ());
// Obtain the last time the session object was accessed.
Out. println ("ID" + session. GETID () + "");
// Obtain the session ID and print it
Out. println ("created:" + created + "");
// Print the session Creation Time
Out. println ("Last accessed:" + accessed + "");
// Print the last access time

Session. setattribute ("uid", "12345678 ");
// Add the variable uid = 12345678 TO THE SESSION
Session. setattribute ("name", "Tom ");
// Add the variable name = Tom to the session

Enumeration E = session. getattributenames ();
// Obtain the enumerated object of the variable name in the session.
While (E. hasmoreelements () {// traverse every variable
String name = (string) E. nextelement (); // obtain the name first.
String value = session. getattribute (name). tostring ();
// Obtain the value from the session by name
Out. println (name + "=" + value + ""); // print
}
Out. println (""); // print the HTML Tag
Out. println ("");
}
}
}

The servlet runs as follows:
 

With the session object, the Web application can save the customer's status on the server side. This is important for building Web applications. In the future, readers will gradually learn about it. As mentioned above, session is just a concept and there are many implementation methods. Here we will not discuss it much. Because servlet itself is a very practical content, a variety of techniques and implementation solutions are not uncommon. In addition, many related content is not just the servlet patent. This article only gives a brief introduction here, so that readers can have a conceptual understanding of servlet. Interested readers can refer to relevant books

Related Article

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.