Data sharing between servlets

The realization scheme of data sharing between Servlets

1. Data sharing: After the work of OneServlet is completed, the generated data is handed over to TwoServlet for use

2. Four data sharing schemes are provided in the Servlet specification:

        1) ServletContext interface

        2) Cookie category

        3) HttpSession interface

        4) HttpServletRequest interface

ServletContext interface

 1 Introduction:

        1) An interface from the Servlet specification. Exists in servlet-api.jar in Tomcat

        Responsible for providing the implementation class of this interface in Tomcat

        2) If two Servlets come from the same website . Between each other through the ServletContext in the website

        Instance objects to realize data sharing.

        3) Developers are used to calling the ServletContext object [global scope object]

    2. Working principle:

        Every website has a global scope object.

        This global effect on the object is [equivalent to] a Map .

        In this website OneServlet can store a piece of data in the global scope object, in the current website

        At this time, other servlets can get this data from the global scope object for use.

    3. Acoustic life cycle of global scope objects (not created by yourself)

        1) During the startup of the Http server, a global scope object is automatically created in memory for the current website

        2) During the operation of the Http server, a website has only one global scope object

        3) During the operation of the Http server, the global scope object has been alive

        4) When the Http server is about to shut down, it is responsible for destroying the global scope objects in the current website

        ******The life cycle of the global scope object runs through the entire runtime of the website ***** *

    4. Command realization:

        [Same website] OneServlet shares data with TwoServlet

        OneServlet{

            protected void doGet(HttpServletRequest request,HttpServletResponse response){

                //1. Ask Tomcat for the [global scope object] in the current website through the request object

                ServletContext application=request.getServletContext();

                //2, add the data to the global scope object as [shared data]

                application.setAttribute("key1","数据");

            }

        }

        TwoServlet{

            protected void doGet(HttpServletRequest request,HttpServletResponse response){

                //1. Ask Tomcat for the [global scope object] in the current website through the request object

                ServletContext application=request.getServletContext();

                //2, get the data corresponding to the specified keyword from the global scope object

                Object obj=application.getAttribute("key1");

            }

        }

Code display

public class OneServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s="abc";
        //通过请求对象获取全局作用域对象
        ServletContext application=request.getServletContext();
        //将数据添加到全局作用域对象中
        application.setAttribute("key1",s);
    }
}


public class TwoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=null;
        //通过响应对象获取全局作用域对象
        ServletContext application=request.getServletContext();
        //通过全局作用对象来回去数据
        String s=(String)application.getAttribute("key1");
        response.setContentType("text/html");
        out=response.getWriter();
        System.out.println(s);
        out.print(s);
    }
}

Cookie class

1 Introduction:

        A tool class 1) Cookie from Servlet specification is present in Tomcat provided servlet-api.jar in

        2) If two Servlets come from the same website and provide services for the same user/browser , you can use

        Cookie object for data sharing

        3) Cookies store the private data of the current user, and improve the quality of service in the process of sharing data

        4) In real life scenarios, Cookie is equivalent to the [membership card] that the user gets on the server

    2. Related principles:

        The user sends a request to the myWeb website to apply for OneServlet for the first time through the browser.

        OneServlet creates a Cookie during operation to store data related to the current user

        After the OneServlet work is completed, [write the cookie into the response header] to return it to

        Current browser.

        After the browser receives this response packet, it stores the Cookie in the browser's cache.

        After a period of time, the user sends a request to the myWeb website again to apply for TwoServlet through the same browser.

        [The browser needs to unconditionally write the cookie that was previously pushed by the myWeb website into the request header] and send it .

        At this time, when TwoServlet is running, you can get OneServlet by reading the information in the Cookie in the request header

        Shared data provided.

    3. Realize the command:

        OneServlet and TwoServlet in the same website realize data sharing scheme with the help of Cookies

        OneServlet(HttpServletRequest request,HttpServletResponse response){

            protected void doGet{

                //Create a Cookie object to save shared data (shared data of the current user)

                Cookie card=new Cookie("key1","abc");

                Cookie card1=new Cookie("key2","efg");

                ****Cookie is equivalent to a map

                ****Only one key-value pair can be placed in a cookie

                ****The key and value of this key-value pair can only be String

                ****The key in the key-value pair cannot be Chinese

                //Write Cookie into the response header and hand it to the browser

                request.addCookie(card);

                request.addCookie(card1);

                ....

            }

        }

        The browser sends a request to the myWeb website to request access to TwoServlet----->Request package [url:/myWeb/two method:get]

                                                                【

                                                                    Request parameters: ***

                                                                    cookie key1=abc;key2=efg

                                                                】

                                                                【】

                                                                【】

        TwoServlet(HttpServletRequest request,HttpServletResponse response){

            protected void doGet{

                //Call the request object to get the cookie returned by the browser from the request header

                Cookie cookieArray=request.getCookies();

                //Loop through the array to get each cookie

                for(Cookie card:cookieArray){

                    String key=card.getName();

                    String value=card.getValue();

                }

           }

        }

4. Timing of Cookie Destruction

        1) By default, the Cookie object is stored in the browser's cache.

        Only when the browser is closed, the Cookie object is destroyed.

        2) In the case of manual settings, you can ask the browser to accept cookies

        Stored on the hard disk of the client computer. At the same time, you need to specify the cookie on the hard disk

        The survival time of the above, within the survival time range, close the browser, close the client

        The computer, shutting down the server, will not cause the cookie to be destroyed. In survival time

        Upon arrival, the cookie is automatically deleted from the hard drive.

        cookie.setMaxAge(60); indicates that the Cookie object will survive on the hard disk for 60s

Code

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 style="color: red" align="center">登录界面</h1>
<hr>
<form action="/myWeb/one" >
    <table align="center" border="1px">
        <tr>
            <td>用户名</td>
            <td>
                <input type="text" name="userName" />
            </td>
        </tr>
        <tr>
            <td>预存金额</td>
            <td>
                <input type="text" name="money" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="submit" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="reset" value="reset" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>

OnsServlet

package school.xauat.controller;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class OneServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName,money;
        //通过请求对象获取请求参数
        userName=request.getParameter("userName");
        money=request.getParameter("money");
        //创建Cookie对象
        Cookie cookie1=new Cookie("userName",userName);
        Cookie cookie2=new Cookie("money",money);
        //指定cookie对象在硬盘上存活1mins
        //cookie2.setMaxAge(60);
        //通过响应对象将Cookie对象放入响应头中
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        //通过请求转发的方式访问index_1.html
        request.getRequestDispatcher("index_1.html").forward(request,response);
    }
}

index_1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 align="center" style="color:red;">点餐界面</h1>
<hr>
<form action="/myWeb/two">
    <table align="center" border="1px">
        <tr>
            <td><input type="radio" name="food" value="jiaozi" />饺子$30</td>
        </tr>
        <tr>
            <td><input type="radio" name="food" value="miantiao" />面条$25</td>
        </tr>
        <tr>
            <td><input type="radio" name="food" value="gaifan" />盖饭$20</td>
        </tr>
        <tr>
            <td><input type="submit" value="submit" /></td>
        </tr>
    </table>
</form>
</body>
</html>

TwoServlet

package school.xauat.controller;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class TwoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String food,userName = null;
        int money=0;
        Cookie newCookie=null;
        PrintWriter out=null;
        //通过请求对象获取请求参数
        food=request.getParameter("food");
        //获取请求头中的Cookie对象
        Cookie[] cookies=request.getCookies();
        //遍历cookies获取userName和money
        for(Cookie cookie:cookies){
            String key=cookie.getName();
            String value=cookie.getValue();
            if ("userName".equals(key)){
                userName=value;
            }
            if ("money".equals(key)){
                money=Integer.valueOf(value);
            }
        }
        response.setContentType("text/html;charset=utf-8");
        //通过响应对象获取输出流
        out=response.getWriter();
        //根据food的值进行不同的消费
        if ("jiaozi".equals(food)){
            if (money>=30){
                money-=30;
                newCookie=new Cookie("money",String.valueOf(money));
                out.print(userName+"您好,您本次消费30元,余额为:"+money);
                System.out.println(1);
            }else{
                out.print(userName+"您好,您的余额不足,余额:"+money);
            }
        }
        if ("miantiao".equals(food)){
            if (money>=25){
                money-=25;
                newCookie=new Cookie("money",String.valueOf(money));
                out.print(userName+"您好,您本次消费25元,余额为:"+money);
            }else{
                out.print(userName+"您好,您的余额不足,余额:"+money);
            }
        }
        if ("gaifan".equals(food)){
            if (money>=20){
                money-=20;
                newCookie=new Cookie("money",String.valueOf(money));
                out.print(userName+"您好,您本次消费20元,余额为:"+money);
            }else{
                out.print(userName+"您好,您的余额不足,余额:"+money);
            }
        }
        //如果消费成功,将cookie对象通过响应对象加入到响应头中
        if (newCookie!=null){
            response.addCookie(newCookie);
        }
    }
}

HttpSession interface

1 Introduction:

        1) The HTTPSession interface comes from an interface under the Servlet specification, which exists in servlet-api.jar in Tomcat

        The related implementation classes are provided by the Http server. The implementation class provided by Tomcat exists in servlet-api.jar

        2) If two Servlets come from the same website and provide services to the same user/browser , you can use

        HTTPSession object for data sharing

        3) Developers are accustomed to calling the HttpSession interface modification object [session scope object]

2. The difference between HttpSession and Cookie [Interview Questions]

        1) Storage location:

            Cookies are stored in the client computer (browser memory/hard disk)

            HTTPSession is stored in the memory of the server computer

        2) Data type:

            Cookie object storage shared data type can only be String

            HTTPSession object can store any type of shared data Object

        3) The amount of data stored:

            A Cookie object can only store one shared data

            HttpSession uses Map collection to store shared data, so any amount of shared data can be stored

        4) Different reference objects:

            Cookie is equivalent to the customer's [membership card] on the server side. The amount of data is small and the data type is single.

            HTTPSession is equivalent to the customer's [private safe] on the server side

3. Command realization:

        Under the same website (myWeb) OneServlet passes data to TwoServlet

        OneServlet{

            public void doGet(HttpServletRequest request,HttpServletResponse response){

                //Call the request object to ask Tomcat for the session scope object of the current user on the server

                HttpSession session=request.getSession();

                //Add data to the user's session scope object

                session.setAttribute("key1", shared data);

            }

        }

        Browser visits TwoServlet in /myWeb

        OneServlet{

            public void doGet(HttpServletRequest request,HttpServletResponse response){

                //Ask Tomcat for the session scope object of the current user on the server through the request object

                HttpSession session=request.getSession();

                //Get the shared data provided by OneServlet from the session scope object

                Object shared data=session.getAttribute("key1");

            }

        }

Code

The following uses the HttpSession interface to implement the shopping cart function

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车</title>
</head>
<body>
<h1 style="color:red;" align="center">京东</h1>
<hr>
<table align="center" border="1px">
    <thead>
    <tr>
        <td>商品名称</td>
        <td>商品单价</td>
        <td>介绍</td>
        <td>加入购物车</td>
    </tr>
    </thead>
    <tr>
        <td>Dell</td>
        <td>6500</td>
        <td>好东西</td>
        <td><a href="one?product=Dell">加入购物车</a></td>
    </tr>
    <tr>
        <td>Lenovo</td>
        <td>6000</td>
        <td>好东西</td>
        <td><a href="one?product=Lenovo">加入购物车</a></td>
    </tr>
    <tr>
        <td>MacBook</td>
        <td>7000</td>
        <td>好东西</td>
        <td><a href="one?product=MacBook">加入购物车</a></td>
    </tr>
    <tr>
        <td colspan="4" align="center">
            <a href="/myWeb/two">查看我的购物车</a>
        </td>
    </tr>

</table>
</body>
</html>

OneServlet

public class OneServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String product;
        //通过请求对象获取请求头中的请求参数
        product=request.getParameter("product");
        //通过请求对象向Tomcat服务器索要会话作用域对象
        HttpSession session = request.getSession();
        request.getSession(false);
        //将数据添加到会话作用域对象中
        Integer productNum=(Integer)session.getAttribute(product);
        if (productNum==null){
            session.setAttribute(product,1);
        }else{
            session.setAttribute(product,productNum+1);
        }
    }
}

  TwoServlet

public class TwoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通过请求对象获取会话作用域对象
        HttpSession session = request.getSession();
        //从会话作用域对象中读取所有的key值,存放在一个枚举中
        Enumeration<String> products = session.getAttributeNames();
        //循环遍历所有的共享数据
        while(products.hasMoreElements()){
            String product=products.nextElement();
            int productNum=(int)session.getAttribute(product);
            System.out.println("商品名称:"+product+"商品数量:"+productNum);
        }

    }
}

4. How does Http server associate users with HttpSession

        Cookie

5、getSession()和getSession(false)

        1)getSession()

            If the current user already has its own session scope object in the server

            Require Tomcat to return this session scope object.

            If the current user does not have its own session scope object on the server.

            Require Tomcat to create a new session scope object for the current user .

        2)getSession(false)

            If the current user already has its own session scope object in the server

            Require Tomcat to return this session scope object.

            If the current user does not have its own session scope object on the server.

            Tomcat will return a null at this time .

6, HttpSession destruction timing

        1. Cookies used when users associate with HttpSession can only be stored in the browser's cache .

        2. When the browser is closed, it means that the relationship between the user and his HttpSession is cut off .

        3. Tomcat cannot detect when the browser is closed, so when the browser is closed, it will not cause Tomcat to destroy the HttpSession associated with the browser

        4. In order to solve this problem, Tomcat will set the [idle time] for each HttpSession object , this idle time is 30mins by default, if the current HttpSession object

            When the idle time reaches 30mins, Tomcat thinks that the user has given up his HttpSession, at this time Tomcat will destroy the HeepSession.

7. Manual setting of HttpSession idle time

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

        <session-config>

            <session-timeout>5</session-timeout><!--The maximum idle time of each session in the current website is 5mins-->

        </session-config>

HttpServletRequest interface

1 Introduction:

        1) in the same site, if it is passed between two Servlet [] request to forward way calling

        They will share the same request protocol package with each other , and a request protocol package corresponds to only one request object , so

        The two Servlets share the same request object. At this time, the request object can be used between the two Servlets

        Realize data sharing.

        2) When the request object realizes the function of data sharing between servlets, the developer refers to the request object as [request scope object]

2. Command realization:

        OneServlet needs to provide shared data to TwoServlet when applying for forwarding the same request to call TwoServlet

        OneServlet{

            public void doGet(HttpServletRequest request,HttpServletResponse response){

                //Add data to the attribute attribute in the request scope object

                request.setAttribute("key1",data);//The data type can be any type of Object

                //Apply to Tomcat to call TwoServlet

                //Generate application resource file report through request object

                request.getRequestDispatcher("/two").forward(request,response);

            }

        }

        TwoServlet{

            public void doGet(HttpServletRequest request,HttpServletResponse response){

                //Get the shared data written by OneServlet from the current request object

                Object obj=request.getAttribute("key1");

            }

        }

Code

OneServlet

public class OneServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将共享数据添加到请求作用域对象的attribute属性中
        request.setAttribute("key",500);
        //通过请求转发的方式调用TwoServlet
        RequestDispatcher report=request.getRequestDispatcher("/two");
        report.forward(request,response);
    }
}

TwoServlet

public class TwoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通过请求对象获取共享数据
        Integer num=(Integer) request.getAttribute("key");
        System.out.println(num);
    }
}

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_45796208/article/details/108726200