1, Data sharing
1. Overview of data sharing
Data sharing is data transfer. For example, how to transfer data to another Servlet class myservletttwo after MyServletOne is completed becomes data sharing
2. Data sharing solution
(1) ServletContext interface
(2) Cookie class
(3) HttpSession interface
(4) HttpServletRequest interface
2, ServletContext interface
1. Introduction
(1) It comes from an interface in the Servlet specification. There is servlet-api.jar in Tomcat, which is responsible for providing this interface implementation class.
(2) If two servlets come from the same website, they can share data with each other through the Servlet Context instance object of the website
(3) We are used to calling ServletContext objects global scope objects
2. Principle
Each web site has a global scope object. This global scope object is equivalent to a Map
In this website, MyServletOne can store a data into the global scope object. At this time, other servlets in the current website can get this data from the global scope object for use.
3. Life cycle
(1) During the startup of Http server, a global scope object is automatically created in memory for the current website.
(2) When the Http server is running, a web site has only one global scope object.
(3) Global scope objects remain alive while the Http server is running.
(4) When the Http server is ready to shut down, it is responsible for destroying the global scope objects in the current website.
The global scope object life cycle runs through the entire operation of the web site
4. Implement the command
MyServletOne doGet Method: ServletContext application = request.getServletContext();//1. Ask Tomcat for the global scope object in the current website through the request object application.setAttribute("key",data);//2. Add data to the global scope object as shared data MyServletTwo doGet Method: ServletContext application = request.getServletContext();//1. Ask Tomcat for the global scope object in the current website through the request object Object data = application.getAttribute("key");//2. Get the data corresponding to the specified keyword from the global scope object
5. Code example
MyServletOne
package controller; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "MyServletOne", value = "/one") public class MyServletOne extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext application = request.getServletContext(); application.setAttribute("key", 100); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
MyServletTwo
package controller; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "MyServletTwo", value = "/two") public class MyServletTwo extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext application = request.getServletContext(); Integer num = (Integer) application.getAttribute("key"); System.out.println(num); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
We start the Tomcat server, open MyServletOne and then myservletttwo in the browser, and the results are shown in the figure below
3, Cookie class
1. Introduction
(1) Cookie comes from a tool class in Servlet specification and exists in servlet-api.jar provided by Tomcat.
(2) If two servlets come from the same website and provide services for the same browser / user, data sharing is carried out with the help of Cookie objects.
(3) Cookie s store the current user's private data and improve the service quality in the process of sharing data
2. Principle
The user sends a request to the myWeb site for the first time through the browser to apply for myserverletone. During operation, myserveletone creates a Cookie to store data related to the current user. After myserveletone completes its work, it writes the Cookie into the response header and returns it to the current browser. After the browser receives the response package, the Cookie is stored in the browser's cache. After a period of time, when the user sends a request to the myWeb site again through the same browser to apply for myservelettwo, the browser needs to unconditionally write the Cookie pushed by the myWeb site to the request hair. At this time, when myservelettwo is running, it can get the shared data provided by myservelettwo by reading the information in the Cookie in the request header.
3. Implement command
stay MyServletOne doGet Method: Cookie c1 = new Cookie("key1", "abc");//1. Create a Cookie object and save the shared data Cookie c2 = new Cookie("key2", "def");//A Cookie is equivalent to a Map. A Cookie can only store one key value pair, and the key and value types can only be String response.add(c1);//2. Write the Cookie into the response header and give it to the browser response.add(c2); stay MyServletTwo doGet Method: Cookie cArray[] = request.getCookies(); for (Cookie c : cArray) { String key = c.getName(); String value = c.getValue(); System.out.println(key+ " : " + value); }
4.Cookie destruction time
(1) By default, Cookie objects are stored in the browser's cache. Therefore, as long as the browser is closed, the Cookie object is destroyed.
(2) In the case of manual setting, the browser can be required to store the received Cookie on the hard disk of the client computer, and the survival time of the Cookie on the hard disk needs to be specified. Within the lifetime, closing the browser, closing the client computer and closing the server will not cause the Cookie to be destroyed. When the survival time reaches, the Cookie is automatically deleted from the hard disk.
Cookie cookie = new Cookie(); cookie.setMaxAge(60);//Survive on hard disk for one minute
5. Code example
Simulate the user's card payment process for ordering meals in the restaurant
MyServletOne:
package controller; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "MyServletOne", value = "/one") public class MyServletOne extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username, money; username = request.getParameter("username"); money = request.getParameter("money"); Cookie c1 = new Cookie("username", username); Cookie c2 = new Cookie("money", money); response.addCookie(c1); response.addCookie(c2); request.getRequestDispatcher("/order.html").forward(request, response); response.sendRedirect("/order.html"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
MyServletTwo:
package controller; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "MyServletTwo", value = "/two") public class MyServletTwo extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int dumpling = 30; int rice = 2; int noodle = 15; int money = 0, balance = 0, expense = 0; String meal, username = null; Cookie cookieArray[] = null; response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); Cookie c = null; meal = request.getParameter("meal"); cookieArray = request.getCookies(); for (Cookie cookie : cookieArray) { String key = cookie.getName(); String value = cookie.getValue(); if ("username".equals(key)) { username = value; } else if ("money".equals(key)) { money = Integer.valueOf(value); if ("dumpling".equals(meal)) { if (dumpling > money) { out.print("user : " + username + "doesn't have enough money"); } else { c = new Cookie("money", (money - dumpling) + ""); expense = dumpling; balance = money - dumpling; } } } else if ("noodle".equals(meal)) { if (noodle > money) { out.print("user : " + username + "doesb't have enough money"); } else { c = new Cookie("money", (money - noodle) + ""); expense = noodle; balance = money - noodle; } } else if ("rice".equals(meal)) { if (rice > money) { out.print("user : " + username + " does't have enough money"); } else { c = new Cookie("money", (money - rice) + ""); expense = rice; balance = money - rice; } } } response.addCookie(c); out.print("user : " + username + "you have take " + expense + " yuan " + " balance :" + balance); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <center> <font style="color:red;font-size:40px">New users apply for card opening</font> <form action="/myWeb/one"> <table border="2"> <tr> <td>user name</td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>Deposit amount</td> <td><input type="text" name="money"/></td> </tr> <tr> <td><input type="submit" value="Apply for card opening"/></td> <td><input type="reset" /></td> </tr> </table> </form> </center> </body> </html>
order.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <center> <font style="color:red;font-size:40px">order</font> <form action="/myWeb/two"> Food type:<input type="radio" name="meal" value="dumpling"/>dumpling(30yuan) <input type="radio" name="meal" value="noodle"/>noodle(20yuan) <input type="radio" name="meal" value="rice"/>rice(2yuan)<br/> <input type="submit" value="consuming by card"> </form> </center> </body> </html>
The process is as follows
4, HttpSession interface
1. Introduction
(1) The httpsession interface comes from the interface under the Servlet specification. It exists in servlet-api.jar in tomcat, and its implementation class is provided by the Http server. The Tomcat implementation class exists in servlet-api.jar.
(2) If two servlets come from the same website and provide services for the same browser / user, data sharing is carried out with the help of HttpSession object.
(3) We are usually used to calling the object modified by the HttpSession interface as the session scope object
2. Difference between httpsession and Cookie
(1) Storage location:
Cookie s: stored on the client computer (browser memory / hard disk)
HttpSession: stored in the memory of the server computer
(2) Data type:
The Cookie object store shared data type can only be String
The HttpSession Object can store any type of shared data Object
(3) Number of data:
A Cookie object can only store one shared data
HttpSession uses the map collection to store shared data, so you can store any number of shared data
3. Implement command
stay MyServletOne of doGet Method: HttpSession session = request.getSession();//1. Call the request object and ask Tomcat for the HttpSession object session.setAttribute("key1", shared data );//2. Add data to HttpSession stay MyServletTwo of doGet Method: HttpSession session = request.getSession(); Object shared data = session.getAttribute("key1");
4. Principle
When the user accesses the Servlet for the first time, the server will create an independent Session for the user and generate a SessionID. When responding to the browser, the SessionID will be loaded into a cookie and saved to the browser. When the user accesses the Servlet again, the request will carry the Session ID in the cookie to access. The server will check whether there is a corresponding Session object according to the Session ID, take it out for use if there is one, and create a Session if there is none
5.getSession() and getSession(false)
(1) getSession() :
If there is a corresponding Session object, this object is returned. If not, create a new Session object
(2) getSession(false) :
If there is a corresponding Session object, this object is returned. If not, null is returned
6.HttpSession destruction time
(1) The cookies used when the user is associated with HttpSession can only be stored in the browser cache.
(2) When the browser is closed, it means that the relationship between the user and his HttpSession is cut off.
(3) Because Tomcat cannot detect when the browser closes, it will not cause Tomcat to destroy the HttpSession associated with the browser when the browser closes.
(4) In order to solve this problem, Tomcat sets an idle time for each HttpSession object, which is 30 minutes by default. If the current HttpSession object is idle for 30 minutes, Tomcat thinks that the user has abandoned his HttpSession, and Tomcat will destroy the HttpSession
How to manually set the idle time of HttpSession
Insert under web.xml file
<session-config> <session-timeout>5</sesstion-timeout><!--Each in the current web site session Maximum idle time 5 minutes--> <session-config>
5, HttpServletRequest interface
1. Introduction
(1) In the same website, if two servlets are called through request forwarding, they share the same request protocol package with each other. A request protocol package only corresponds to one request object, so servlets share the same request object. At this time, this request object can be used to realize data sharing between two servlets.
(2) When the request object implements the data sharing function between servlets, we usually call the request object request scope object
2. Command implementation
When myserveletone calls myservelettwo through request forwarding, it needs to provide shared data to myservelettwo.
stay MyServletOne of doGet Method request.setAttribute("key1", data);//Add data to the attribute of the request scope object request.getRequestDispatcher("/two").forward(request, response); stay MyServletTwo of doGet Method Object data = request.getAttribute("key1");