The Session object represents a user session. The meaning of a user session is that a session starts when the client browser connects to the server and is disconnected from the server.
A session is usually used to track the user's session information, such as determining whether the user is logged on to the system or in the shopping cart.
Attributes within the session range can be shared between multiple page jumps. Once the browser is closed, that is, the session ends, all attributes within the session range will be lost.
The Session object is an instance of httpsession. There are two common methods for httpsession.
1. setattribute (string attname, object attvalue) sets the value of the attname attribute within the session range to attvalue
2. getattribute (string attname) returns the value of the attname attribute within the session range.
Shopping Cart instance
Shop. jsp ----- add purchase item Page
<Form method = "Post" Action = "processbuy. JSP "> books <input type =" checkbox "name =" item "value =" book "> <br> Computer <input type =" checkbox "name =" item "value = "computer"> <br> Car <input type = "checkbox" name = "item" value = "car"> <br> <input type = "Submit" value = "purchase "> </form>
Processbuy. jsp ----- process the item Page
<% Map <string, integer> itemmap = (Map <string, integer>) session. getattribute ("itemmap"); If (itemmap = NULL) {itemmap = new hashmap <string, integer> (); itemmap. put ("books", 0); itemmap. put ("computer", 0); itemmap. put ("car", 0) ;}// obtain the request parameter string [] buys = request. getparametervalues ("item"); For (string item: buys) {If (item. equals ("book") {int num1 = itemmap. get ("books "). intvalue (); itemmap. put ("books", num1 + 1);} else if (item. E Quals ("computer") {int num2 = itemmap. get ("computer "). intvalue (); itemmap. put ("computer", num2 + 1);} else if (item. equals ("car") {int num3 = itemmap. get ("car "). intvalue (); itemmap. put ("car", num3 + 1) ;}// put the itemmap object to the itemmap attribute session set to the session range. setattribute ("itemmap", itemmap); %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML>
Note: Generally, information related to the user session status should be put into the session range. Do not put the information into the session range just for the exchange of information between two pages. If you only want to exchange information for two pages, you can put the information into the request range and then forward the request after meals. The session mechanism is usually used to save the client status information, which needs to be saved to the hard disk of the Web server. Therefore, the attribute values in the session must be serializable, otherwise, an exception that cannot be serialized will be thrown.