当前位置:网站首页>Cookies and sessions

Cookies and sessions

2022-06-21 18:50:00 LvhaoIT

One 、Cookie

1. Introduce :

​ 1)Cookie From Servlet A tool class in the specification , Exist in Tomcat Provide servlet-api.jar in

​ 2) If two Servlet From the same website , And for the same browser / Service provided by users , here
​ With the help of Cookie Object for data sharing

​ 3) Cookie Store the private data of the current user , Improve the quality of service in the process of sharing data

​ 4) In real life situations ,Cookie It is equivalent to that the user gets 【 Membership card 】

2. principle :
​ For the first time, the user through the browser to MyWeb The website sends a request for OneServlet.
​ OneServlet Create a Cookie Store data related to the current user
​ OneServlet After work ,【 take Cookie Write to the response header 】 Return to the current
​ browser .
​ After the browser receives the response package , take cookie Cache stored in the browser
​ After a while , User pass 【 The same browser 】 Again to 【myWeb Website 】 Send request request TwoServlet when .
​ 【 The browser needs to unconditionally myWeb Pushed by the website before Cookie, Write to request header 】 Send past
​ here TwoServlet At run time , You can read from the request header cookie In the information , obtain OneServlet Provided
​ Shared data

3. Implement the command :

​ Same website OneServlet And TwoServlet With the help of Cookie Implement data sharing

OneServlet{
    
		public void doGet(HttpServletRequest request,HttpServletResponse resp){
    

//1. Create a cookie object , Save shared data ( Current user data )
Cookie card = new Cookie("key1","abc");
Cookie card1= new Cookie("key2","efg");
****cookie Equivalent to one map
**** One cookie Only one key value pair can be stored in the 
**** The key value is right key And value Can only be String
**** The key/value pair key It can't be Chinese 
//2.【 Hairpin 】 take cookie Write to the response header , Give it to the browser 
resp.addCookie(card);
resp.addCookie(card1)
}

}

 browser / user       <--------- Response package  【200】
【cookie: key1=abc; key2=eft】
【】
【 Processing results 】

 Browser direction myWeb The website sends a request to visit TwoServlet----> Request package  【url:/myWeb/two method:get】
【
 Request parameters :xxxx
Cookie   key1=abc;key2=efg
】
【】
【】
TwoServlet{
    

public void doGet(HttpServletRequest request,HttpServletResponse resp){
    

//1. Call the request object to get the returned from the browser from the request header Cookie
Cookie  cookieArray[] = request.getCookies();
//2. Loop through the data to get each cookie Of key  And  value
for(Cookie card:cookieArray){
    
String key =   card.getName();  Read key  "key1"
Strign value = card.getValue(); Read value "abc"
 Provide better service ........
}
}
}

4.Cookie Destruction opportunity :

​ 1. By default ,Cookie Objects are stored in the browser's cache .
​ So as long as the browser closes ,Cookie The object is destroyed

​ 2. In case of manual setting , You can ask the browser to receive Cookie
​ Stored on the hard disk of the client computer , At the same time, you need to specify Cookie
​ Survival time on hard disk . Within the lifetime , Close the browser
​ Shut down the client computer , Shut down the server , It doesn't lead to Cookie
​ Be destroyed . When the survival time arrives ,Cookie Automatically from the hard disk
​ Delete

cookie.setMaxAge(60); //cookie Survive on the hard disk 1 minute 

5.Cookie understand :

	*  First of all, for Cookie,cookie It's not safe , It can be modified artificially 
	*  need Cookie If your page doesn't get Cookie Parameters , Will report 500 wrong 
	* Cookie It will be destroyed when the browser is closed 

6.Cookie example —— Ordering membership card

oneServlet

public class oneServlet extends javax.servlet.http.HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    

        //1. Call the request object to read 【 Request parameters 】 Information 
        String userName, money;
        userName = request.getParameter("userName");
        money = request.getParameter("money");
        //2. activate a bank card 
        Cookie card1 = new Cookie("userName", userName);
        Cookie card2 = new Cookie("money", money);
        //3. Hairpin , take Cookie Write to the response header and give it to the browser 
        response.addCookie(card1);
        response.addCookie(card2);
        //4. Notify the browser to write the content of the order page into the response body and give it to the browser ( Request forwarding )
        request.getRequestDispatcher("/index_2.html").forward(request, response);


    }
}

twoServlet

/** * Created by IntelliJ IDEA. * User: LvHaoIT (asus) * Date: 2021/5/5 * Time: 14:14 */
public class twoServlet extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        double jiaozi_money = 30;
        double gaifan_money = 21;
        double miantiao_money = 20;
        double money = 0;
        double xiaofei = 0;
        String food, userName = null;

        // Modify the response body character set 
        response.setContentType("text/html;charset=utf-8");
        // Get output stream object 
        PrintWriter out = response.getWriter();
        // Define a new Cookie, Overwrite the previous with the newly processed value cookie
        Cookie newCard = null;

        //1. Read request header parameter information , Get the type of food the user ordered 
        food = request.getParameter("food");
        //2. Read... In the request Cookie
        Cookie[] cookieArray = request.getCookies();// Remove all cookie
        //3. Credit card consumption 
        for (Cookie card : cookieArray) {
    
            // Take out the data and process it accordingly 
            String key = card.getName();// obtain key
            String value = card.getValue();// obtain value
            // Determine whether the retrieved user name is the user name 
            if (key.equals("userName")) {
    
                // Is the user name 
                userName = value;// Find the corresponding user name 
            } else if (key.equals("money")) {
    // What you take out is money
                money = Double.valueOf(value); // Save your money 
                // Start spending  food There is the name of the food 
                if (food.equals(" dumplings ")) {
    
                    // I ordered dumplings , But we need to judge whether the money is enough 
                    if (money < jiaozi_money) {
    
                        out.print(" user " + userName + " Lack of balance , Please top up !");
                    } else {
    
                        // Enough money , Can consume 
                        newCard = new Cookie("money", (money - jiaozi_money) + "");
                        xiaofei = jiaozi_money;
                    }
                } else if (food.equals(" noodles ")) {
    
                    // I ordered dumplings , But we need to judge whether the money is enough 
                    if (money < jiaozi_money) {
    
                        out.print(" user " + userName + " Lack of balance , Please top up !");
                    } else {
    
                        // Enough money , Can consume 
                        newCard = new Cookie("money", (money - miantiao_money) + "");
                        xiaofei = miantiao_money;
                    }
                } else if (food.equals(" Cover rice ")) {
    
                    // I ordered dumplings , But we need to judge whether the money is enough 
                    if (money < jiaozi_money) {
    
                        out.print(" user " + userName + " Lack of balance , Please top up !");
                    } else {
    
                        // Enough money , Can consume 
                        newCard = new Cookie("money", (money - gaifan_money) + "");
                        xiaofei = gaifan_money;
                    }
                }
            }
        }
        //4. Return the user's membership card 
        response.addCookie(newCard);
        //5. The consumption record is written to the response object 
        out.println(" user " + userName + " This consumption :" + xiaofei + "  The balance in the card remains :" + (money - xiaofei));
    }
}

Test the web :

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title> New users open cards </title>
</head>

<body>
<center>
    <font style="color: red;font-size:40px ;"> New members open cards </font>
    <form action="/myCookie/one" method="GET">
        <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 a card "/>
                </td>
                <td>
                    <input type="reset" name=" Reset "/>
                </td>
            </tr>
        </table>

    </form>
</center>


</body>

</html>

index_2.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title> Order page </title>
</head>

<body>
    <center>
        <font style="color: red;font-size: 40px;"> Order page </font>
        <form action="/myCookie/two">
             Type of food :
            <input type="radio" name="food" value=" dumplings " /> dumplings (30 element )<br>
            <input type="radio" name="food" value=" noodles " /> noodles (20 element )<br>
            <input type="radio" name="food" value=" Cover rice " /> Cover rice (21 element )<br>
            <input type="submit" value=" Membership card consumption " />
        </form>
    </center>

</body>

</html>

Implementation schematic diagram

 Insert picture description here

Two 、HttpSession Interface :

1. Introduce :
​ 1)HttpSession Interface from Servlet Standardize the next interface . Exist in Tomcat in servlet-api.jar
​ Its implementation class consists of Http Provided by the server .Tomcat The provided implementation class exists in servlet-api.jar

​ 2) If two Servlet From the same website , And for the same browser / Service provided by users , here
​ With the help of HttpSession Object for data sharing

​ 3) Developers are used to putting HttpSession Interface decorated objects are called 【 Session scope object 】

2.HttpSession And Cookie difference :【 Interview questions 】

​ 1) Storage location : One in the sky , One is underground

​ Cookie: Stored on the client computer ( Browser memory / Hard disk )
​ HttpSession: Stored in the server computer memory

​ 2) data type :
​ Cookie Object storage shared data type can only be String
​ HttpSession Object can store any type of shared data Object

​ 3) Number of data :
​ One Cookie Object can only store one shared data
​ HttpSession Use map Collections store shared data , So you can
​ Store any amount of shared data

​ 4) object of reference :
​ Cookie It is equivalent to the customer on the server side 【 Membership card 】

​ HttpSession It is equivalent to the customer on the server side 【 Private safe 】

3. Command implementation : Same website (myWeb) Next OneServlet Transfer data to TwoServlet

OneServlet{
    

public void doGet(HttpServletRequest request,HttpServletResponse response){
    

//1. Call the request object to Tomcat Ask for the private locker of the current user on the server 
HttpSession   session = request.getSession();
//2. Add data to the user's private locker 
session.setAttribute("key1", Shared data )

}

}

 Browser access /myWeb in TwoServlet

TwoServlet{
    

public void doGet(HttpServletRequest request,HttpServletResponse response){
    
//1. Call the request object to Tomcat Ask for the private locker of the current user on the server 
HttpSession   session = request.getSession();
//2. Get... From the session scope object OneServlet Shared data provided 
Object  Shared data  = session.getAttribute("key1");
}

}

4.Http How the server connects users to HttpSession Connect

cookie

 Insert picture description here

​ **5.getSession() And getSession(false)** difference

​ 1)getSession(): If the current user already has his own private locker on the server .
​ requirement tomcat Return this private locker
​ If the current user is on the server Not owned yet Own personal lockers
​ requirement tocmat For the current user Create a New private lockers

​ 2)getSession(false): If the current user already has his own private locker on the server .
​ requirement tomcat Return this private locker
​ If the current user is on the server Not owned yet Own personal lockers
​ here Tomcat take return null

6.HttpSession Destruction opportunity :

​ 1. Users and HttpSession Used in association Cookie Can only be stored in the browser cache .
​ 2. When the browser closes , It means that the user and his HttpSession The relationship is cut off
​ 3. because Tomcat Unable to detect when the browser closes , Therefore, when the browser is closed, it will not
​ Lead to Tomcat Associate the browser with HttpSession To destroy
​ 4. To solve this problem ,Tomcat For every one HttpSession Object settings 【 free time 】
​ This idle time defaults to 30 minute , If at present HttpSession Object idle time reached 30 minute
​ here Tomcat Think users have given up their HttpSession, here Tomcat Will destroy
​ Drop this HttpSession

7.HttpSession Idle time is manually set

 On the current website /web/WEB-INF/web.xml

<session-config>
<session-timeout>5</session-timeout> 
<!-- Every in the current website session Maximum free time 5 minute -->
</session-config>

Implementation examples

oneServlet

/** * Created by IntelliJ IDEA. * User: LvHaoIT (asus) * Date: 2021/5/5 * Time: 16:59 */
public class oneServlet extends HttpServlet {
    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        //1. Call request object , Read request header parameters 
        String goodsName;
        request.setCharacterEncoding("utf-8");
        goodsName = request.getParameter("goodsName");
        System.out.println(" Entered a breakpoint 1!!");
        //2. Call request object , towards tomcat Ask for a private locker 
        HttpSession session = request.getSession();
        //3. Add the items purchased by the user to the current private locker 
        Integer goodsNum = (Integer) session.getAttribute(goodsName);// Take the quantity of goods 
        // Judge whether the product is put in for the first time 
        if (goodsNum == null) {
    
            session.setAttribute(goodsName, 1);
        } else {
    
            // There was , Then add one 
            session.setAttribute(goodsName, goodsNum + 1);
        }
    }
}

twoServlet

/** * Created by IntelliJ IDEA. * User: LvHaoIT (asus) * Date: 2021/5/5 * Time: 17:11 */
public class twoServlet extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        //1. Call request object , towards tomcat Ask for the private locker of the current user on the server 
        HttpSession session = request.getSession();
        System.out.println(" Entered a breakpoint 2!!");
        //2. take session All of the key out , Stored in an enumeration object 
        Enumeration goodNames = session.getAttributeNames();
        //hasMoreElements() If and only if this enumeration object also contains at least one providable element , To return to  true; Otherwise return to  false.
        while (goodNames.hasMoreElements()) {
    
            //E nextElement()
            // If this enumeration object has at least one element available , The next element of this enumeration .
            String goodName = (String) goodNames.nextElement();// Take out the next trade name 
            int goodsNum = (int) session.getAttribute(goodName);// Take the number of pieces corresponding to the product name 
            System.out.println(" Name of commodity :" + goodName + " The number :" + goodsNum);

        }
    }
}

Test the web

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<table border="2" align="center">
    <tr>
        <td> Name of commodity </td>
        <td> item pricing </td>
        <td> Supplier </td>
        <td> Put it in the shopping cart </td>
    </tr>
    <tr>
        <td> Huawei laptop pro13</td>
        <td>7000</td>
        <td> Huawei </td>
        <td><a href="/myweb/one?goodsName= Huawei laptop pro13"> Put it in the shopping cart </a></td>
    </tr>
    <tr>
        <td> durian </td>
        <td>200</td>
        <td> Thailand </td>
        <td><a href="/myweb/one?goodsName= durian "> Put it in the shopping cart </a></td>
    </tr>
    <tr>
        <td> Men's underwear </td>
        <td>1000</td>
        <td> Zhufangcheng </td>
        <td><a href="/myweb/one?goodsName= Men's underwear "> Put it in the shopping cart </a></td>
    </tr>
    <tr align="center">
        <td colspan="4">
            <a href="/myweb/two"> Check out my shopping cart </a>
        </td>
    </tr>
</table>

</body>

</html>

Implementation schematic diagram :

 Insert picture description here

原网站

版权声明
本文为[LvhaoIT]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211712399430.html