Use of Session and scope in JSP

  • 2020-06-12 10:16:30
  • OfStack

Almost all Web development languages support Session functionality, and Servlet is no exception. The Session functionality in Servlet/JSP is implemented through the concept of scope (scope).

The scope is divided into four types, which are respectively:

page Valid on current page (for JSP only) request Valid in the current request session Valid in the current session application It works in all applications
Doesn't that make sense? Since page is only used in JSP, only the other three scopes are described here. The first point to declare is "scope", which means the extent to which a piece of information is valid.

On the 1st, Wu Song came to Jingyang Gang. He saw a banner fluttering in the wind. On the banner was written five characters, "3 bowls do not make a post". Wu Song shouted: "Shopkeeper, take three bowls of wine, and cut two jin of cooked beef!" The shopkeeper replies, "Three bowls of good wine, two jin of cooked beef." The chef cuts the beef quickly. The shopkeeper pours three bowls of wine and the shopkeeper serves it.

Wu Song gu Dong gu Dong even dry 3 bowls, call 1 "good wine! Shopkeeper, three bowls more!" Small 2 busy pour 3 bowls of good wine again, Wu Song 1 drink and finish. In this way, Wu Song 1 drank a total of 108 wrist. Paid the bill just want to go, shop small 2: "guest officer, there are big worms on the mountain in front of this, guest officer just drank 108 bowls of wine I'm afraid not post, as in the shop stay 1 night, until tomorrow and Orion 1 with the post is not good?"

After Wu Song said what to leave you to remember. In this section of Wu Song fighting tiger, do you see something familiar?

The & # 8226; Wu Song: Browser.
The & # 8226; Tavern: Server.
The & # 8226; Chef: Servlet or JSP.
The & # 8226; Three bowls of good wine! : The browser makes an HTTP request to the server.
The & # 8226; Small shop 2 serving wine: server response.
The & # 8226; Wu Song from entering to leaving: 1 HTTP session (Session).
As we can see, the most basic unit of Web interaction is the HTTP request (' Wu Song order '). The process of each user entering and leaving the site is called one HTTP session (" Wu Song enters and leaves the site "), and there will be multiple users visiting the server during the operation process, that is, multiple HTTP sessions (" Of course, the tavern cannot only receive one customer wu Song "). Then the scope can be understood as:

request HTTP requests the start to end period session The time between the start and end of the HTTP session application The time between startup and shutdown of the server
request
1 HTTP request processing may require multiple Servlet cooperation (" wu song order shop small 2 shall order the kitchen "), a few Servlet between information could be sent through a certain way (" shop is small 2 we will notify the kitchen by Shouting "), but this information at the end of the request is invalid (" kitchen after finished the dishes don't have to tube about this dish ").

Information sharing between Servlet is achieved through two methods of the HttpServletRequest interface:

void setAttribute(String name, Object value)

Save the object value to the request scope with the name name.

Object getAttribute(String name)

Gets the information for the specified name from the request scope.

The first argument to the doGet() and doPost() functions is the HttpServletRequest object, whose setAttribute can be used to pass information.

So once the information is set, how do you pass it on to other Servlet? This USES the forward method of the RequestDispatcher interface to forward requests to other Servlet.

RequestDispatcher ServletContext.getRequestDispatcher(String path)

Get Dispatcher for forwarding. path for the purpose of forwarding Servlet.

void RequestDispatcher.forward(ServletRequest request, ServletResponse response)

Forward request and response.

Therefore, as long as setAttribute, forward and getAttribute are used in the current Servlet, then getAttribute is used in the Servlet.

PHP programmers may have trouble understanding this paragraph because there is no concept of forwarding in PHP and a request can only be processed by one PHP file, so there is no concept of request scope in PHP at all. In contrast to Servlet, requests can be forwarded arbitrarily in the application, so the request scope is used to pass information between different Servlet. Two points to note:

1. Forwarding is not a redirection. Forwarding is done within the Web application. PHP supports redirection but does not forward.
2. Forwarding is transparent to the browser, meaning that no matter how it is forwarded on the server, the browser's address bar still displays the original Servlet address.

session
The session scope is relatively easy to understand. The session scope is the one that is accessed multiple times in the same browser, and the information is passed between those visits. (Every time Wu Song orders, the accountant must write down 1 account, and wait for Wu Song to leave before checking out. This account is valid throughout Wu Song's meal, i.e. it is located in session scope)

session is implemented through the HttpSession interface.

Object HttpSession.getAttribute(String name)

Get information from session

void HttpSession.setAttribute(String name, Object value)

Save the information to session

The HttpSession object is obtained through the HttpServletRequest.getSession () method.

HttpSession HttpServletRequest.getSession()

Gets the object of session where the current request is located.

session start to judge (browser first HTTP requests can think session), but the end is bad judgement (because the browser is closed not notification server "closed, I can end the session"), so only in this way: if a set period of time the client don't respond, thinks that the end of the session. The default value for Tomcat is 120 minutes, but this value can also be set via HttpSession's setMaxInactiveInterval() method.

void setMaxInactiveInterval(int interval)

Sets the timeout value for the session.

If you want to actively end the session, such as when the user clicks Logout, you can use invalidate() method of HttpSession:

void invalidate()

Force end current session.

application
The application scope is the entire time from server startup to shutdown, and the information set within this scope can be used by all applications. (The restaurant checks out after closing, using all the information available between opening and closing.)

Remember ServetContext from the last section? It is through ServetContext that information is passed over the application scope.

Object getAttribute(String name)

Get information from application.

void setAttribute(String name, Object value)

Set the information to the application scope.

conclusion
As you can see, in addition to implementing different interfaces and having different meanings, the usage and function of each scope are the same, and information is transmitted through getAttribute and setAttribute methods.

scope meaning Implementing an interface request HTTP request within HttpServletRequest session HTTP within the session HttpSession application Within the server life cycle ServletContext

The sample program

The sample program
The sample program in this section is a simulation of a user login. Lots of files.

The & # 8226; login. html login form
The & # 8226; DoLogin.java handles the login action of Servlet
The & # 8226; LoginSuccess.java for displaying login success information
The & # 8226; SessionTest.java handler after login
The & # 8226; DoLogout.java logout handler
In order to demonstrate the usage of each scope of request, application and session, data transmission was carried out between Servlet in the following way:

The data generated Data to accept The data content scope DoLogin LoginSuccess The login time request DoLogin SessionTest Login username session DoLogin SessionTest System login frequency application
Visit http: / / localhost: 8080 / LearnJSP/sessiontest charlee enter the user name and password when login 123456 can.

Example download: ES267en-test_jb51ES270en.zip


Related articles: