Session management using the Java Servlet API
The javax.servlet.http.httpsession interface encapsulates the details of the HTTP session, which is related to multiple requests for the web server with a specific web customer within a period of time. The management session data mainly involves three aspects: session exchange, session restarting and session persistence, only data objects that implement the java.io.Serializable interface can be exchanged, relocated, and hold. This interface is primarily the ability of the object to be serialized, which can write status information of the object such as files, network connections, etc.
Programming: Below is an example of a simple shopping mall, when the user purchases the product (candy, radio and exercise book) into the shopping bag, save the purchased product information.
SHOWBUY.JAVA source code is as follows:
import javax.servlet *;. import javax.servlet.http *;. import java.io *;. import java.util *;. public class ShowBuy extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, java .ioException {string [] Item = {"Candy", "Radio", "Exercise Book"}; // Get Session Object HttpSession Session = Req.getSession (TRUE); // Get Selected Product Number Integer Itemcount = (Interger) Session.getValue ("itemcount"); // If the number is not placed in 0 if (itemcount == null) {itemcount = new integer (0);} // set the content type of the response response .setContentType ( "text / html; charset = gb2312"); PrintWriter out = res.getWriter (); // form information acquired String [] itemsSelected POST up; String itemName; itemsSelected = req.getParameterValues ( "item"); // Put the selected item into the session object if (itemsselected! = Null) {for (INT i = 0; i // Remove the product name out.println (items [integer.parseint (item)]); out.println (" ) The goods you put in the shopping bag are: h1> < / center> "); // Write the content of the shopping bag for the page for (int i = 1; i
");} // wrap up out.println (" body>"); OUT. Println (" html>"); out.close ();} The source code for the client's showbuy.html is as follows: department store h1> center>