JavaWeb Session Technology

 

Conversational technology

    1.  Session: A session contains multiple requests and responses.

           A session: the browser sends a request to the server resource for the first time, and the session is established until one party disconnects

    2.  Function: Share data between multiple requests within the scope of a session

    3.  Way:

          1.  Client session technology: Cookie

          2.  Server-side session technology: Session

Cookie:

1.  Concept: client session technology, save data to the client

2.  Quick start:

            1.  Create a Cookie object and bind data

                 new Cookie(String name, String value) 

            2.  Send Cookie Object

                 response.addCookie(Cookie cookie) 

            3.  Get Cookies, get data

                 Cookie[]  request.getCookies()  

3.  Implementation principle

             Implementation based on response header set-cookie and request header cookie

4. Matters needing attention:

              1. You can send multiple cookies at once. You can create multiple Cookie objects, and use response to call the addCookie method multiple times to send cookies .

              2. How long the cookie is saved in the browser. Use the setMaxAge(int seconds) method to write the cookie data to a file on the hard disk and specify the cookie survival time

              3. By default, multiple web projects are deployed in a tomcat server, then cookies cannot be shared among these web projects. If you want to share , set the current virtual directory through setPath(String path) : path is set to "/"

              4. The problem of cookie sharing between different tomcat servers? Use the setDomain(String path) method : If the first-level domain name is set to be the same, then cookies can be shared between multiple servers

5.  The characteristics and functions of cookies

        1.  Cookies store data in the client browser

        2. The  browser has a limit on the size of a single cookie (4kb) and also has a limit on the total number of cookies under the same domain name (20)

        a.  Cookies are generally used to store a small amount of less sensitive data

        b.  Complete the server's identification of the client without logging in

Code

//记录电脑上次打开网页的时间

@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应体格式与编码
        resp.setContentType("text/html;charset=utf-8");
        //获取cookie
        Cookie[] cookies = req.getCookies();
        boolean flag=false;
        //遍历cookie数据
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                //判断名称中是否有:lastTime
                if ("lastTime".equals(name)){
                    //设置Cookie的value,下一次使用
                    flag=true;
                    Date date=new Date();
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    //tomcat不支持特殊字符,需要通过URL编码
                    System.out.println("编码前 "+str_date);
                    str_date=URLEncoder.encode(str_date,"utf-8");
                    System.out.println("编码后"+str_date);

                    //新值串回去,设置存活时间
                    cookie.setValue(str_date);
                    cookie.setMaxAge(60*60*24);
                    resp.addCookie(cookie);
                    //有,欢迎光临,上次登录时间
                    String value = cookie.getValue();
                    //URL 解码
                    value=URLDecoder.decode(value,"utf-8");
                    resp.getWriter().write("<h1>欢迎回来,您上一次的访问时间是:"+value+"</h1>");
                    break;
                }
            }
        }
        if (cookies==null || cookies.length==0 || flag==false){
            //第一次访问
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);

            //tomcat不支持特殊字符,需要通过URL编码
            System.out.println("编码前 "+str_date);
            str_date=URLEncoder.encode(str_date,"utf-8");
            System.out.println("编码后"+str_date);

            Cookie cookie=new Cookie("lastTime",str_date);
            //新值串回去,设置存活时间
            cookie.setValue(str_date);
            cookie.setMaxAge(60*60*24);
            resp.addCookie(cookie);

            resp.getWriter().write("<h1>您好,欢迎您首次访问</h1>");
        }

    }
  }

Session:

1.  Concept: server-side conversation technology, sharing data between multiple requests in a session, and saving the data in server-side objects. HttpSession

2.  Quick start:

        1.  Get the HttpSession object:

            HttpSession session = request.getSession();

        2.  Use the HttpSession object:

            Object getAttribute(String name)  

            void setAttribute(String name, Object value)

            void removeAttribute(String name)  

3.  Principle

           The realization of Session is dependent on Cookie.

4. Details:

        1. When the client is closed, the server is not closed, is the same session obtained twice?

                by default. It's not.

                If you need the same, you can create a Cookie, the key is JSESSIONID, set the maximum survival time, and make the cookie persistent.

                    Cookie c = new Cookie("JSESSIONID",session.getId());

                    c.setMaxAge(60*60);

                    response.addCookie(c);

        2. The client does not close, after the server is closed, is the same session obtained twice?

            Not the same, but make sure that the data is not lost. Tomcat automatically completes the following tasks

                 Passivation of session:  before the server is shut down normally, the session object is serialized to the hard disk

                 Activation of session:  After the server is started, the session file can be converted into a session object in memory.

        3. When will the session be destroyed?

            1. The  server is shut down

            2. The  session object calls invalidate().

            3. The  default session expiration time is 30 minutes

5.  The characteristics of session

           1. The  session is used to store the data of multiple requests for a session, and it is stored on the server side

           2. The  session can store any type and size of data

Code

@WebServlet("/SessionDemo1")
public class SessionDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //session
        HttpSession session = request.getSession();
        session.setAttribute("msg","hello session");
        //请求转发(这个是在一个URL中)
        request.setAttribute("reqmsg","hello req.session");
        request.getRequestDispatcher("/SessionDemo3").forward(request,response);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
    }
}


@WebServlet("/SessionDemo3")
public class SessionDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取数据
        HttpSession session = request.getSession();
        Object msg = session.getAttribute("msg");
        System.out.println(msg);
        //请求转发
        Object reqmsg = request.getAttribute("reqmsg");
        System.out.println(reqmsg);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
    }
}

The difference between session and cookie:

         1. The session stores data on the server side, and the cookie on the client side

         2. There is no data size limit for session, cookies have

         3. Session data is safe, cookies are relatively insecure

         4. The session will be saved on the server for a certain period of time. When the number of visits increases, it will take up the performance of your server. To reduce server performance, cookies should be used.

It is not easy to create. If this blog is helpful to you, please remember to leave a message + like it.

    

Guess you like

Origin blog.csdn.net/promsing/article/details/113729894