Home >Java >javaTutorial >How does JAVA operate Session variables in JSP through Servlet?
Use Servlet to control the session Maintaining session state is a problem that must be faced when developing Web applications. There are many ways to solve this problem. For example, using cookies, hidden type form fields, or directly adding status information to the URL, etc., and the Servlet itself provides an HttpSession interface to support the maintenance of session state. Here we mainly introduce the management of session state based on this interface. Session was invented to fill the limitations of the HTTP protocol. Please note how the HTTP protocol works - the user makes a request and the server responds. This connection between the client and the server is discrete and discontinuous. The HTTP protocol does not provide functionality that allows the server to track user requests. After the server completes responding to the user's request, the server cannot continue to maintain a connection with the browser. From the server side, each request is independent, so the HTTP protocol is considered a stateless protocol. When a user switches between multiple homepages, the server cannot know his identity. The emergence of Session is to make up for this limitation. Using Session, you can save a user's information when he switches between multiple homepages. This makes many things that were impossible to do before become much easier. During the period from when a visitor arrives at a specific homepage to when he leaves, each visitor will receive a separate Session. (2) Write the session variable. You can use the method HttpSession.setAttribute(name, value) to store a piece of information in the Session. You can also use HttpSession.putValue(name, value), but this method is obsolete. (3) Read Session variable. You can use the method HttpSession.getAttribute(name) to read the value of a variable in the Session. If name is an undefined variable, null is returned. It should be noted that the variable type read from getAttribute is Object, and forced type conversion must be used, such as: (4) Close the session. After using the session, you can use the session.invalidate() method to close the session. But this is not strictly required. Because the Servlet engine automatically closes seesion after a period of time. The following is a simple example to illustrate the use of session Out.println(""); //Get the time when the session object was last accessed session.setattribute ("uID", "12345678");
|
The above is the detailed content of How does JAVA operate Session variables in JSP through Servlet?. For more information, please follow other related articles on the PHP Chinese website!