Let the different servlet share the connection in one session

Source: Internet
Author: User
Tags object

= = = = = = = = Problem

If you want to write a shopping cart, you usually need to write a number of different features of the servlet. For example, user login, add goods, check shopping cart, checkout and so on.

You need to read and write the database in these servlet. If we are connected in each servlet-> read-write-> disconnected operation, will consume a lot of server resources, not only the program response speed slows down, but also can aggravate the server and the database burden.

= = to put hope in HttpSession = =

As we have learned, the Servlet API provides methods and classes to specialize in short-term session tracking. Each user of the site is associated with a Javax.servlet.http.HttpSession object that the servlet uses to record and retrieve information for each user.

Luckily, we can store any Java object in the Session object. The methods of storage are already familiar, that is, using the SetAttribute () method. Connection, which represents the database connection, is no exception.

This gives us the hope that the different servlet will share the links within a session.

= = = = = = = Safety Problem

So, just do it as follows?

1. In Servlet1, set a property to the session:

Session.setattribute ("Connection", connection);

2. In Servlet2, remove this attribute:

Connection Connection = (Connection) session.getattribute ("Connection");

Theoretically, no problem. The Connection object produced in the Servlet1 can continue to be used in Servlet2.

But if Servlet2 accidentally changes the connection reference, such as connection = NULL; So, when it puts this connection into the properties of the session again, the other servlet gets a null-pointing connection!

the solution = = = = = = =

It seems not safe to pass the connection directly in the session.



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.