javaweb-Cookie&Session-35

Change the idea code template

Insert picture description here

Conversational technology

1. 会话:一次会话中包含多次请求和响应。
	* 一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止
2. 功能:在一次会话的范围内的多次请求间,共享数据
3. 方式:
	1. 客户端会话技术:Cookie
	2. 服务器端会话技术:Session

Cookie:

1. 概念:客户端会话技术,将数据保存到客户端

2. 快速入门:
3. 实现过程:客户端申请,服务器响应,数据存储在本地,下次访问将存储在本地的数据一并发送过去,实现多次请求响应的数据共享,服务器发送和接收cookie
	* 使用步骤:
		1. 创建Cookie对象,绑定数据
			* new Cookie(String name, String value) 
		2. 发送Cookie对象
			* response.addCookie(Cookie cookie) 
		3. 获取Cookie,拿到数据
			* Cookie[]  request.getCookies()  

I made a mistake when using super?
Encapsulated cookie

package learn.myweb;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//使用注解可以更加简便。其中有默认参数,例如loadstarup
@WebServlet("/head_easy")
//可以更加简化,将url省略掉,使用value就可以,进一步value也不用写
public class servlet_test extends HttpServlet {
    
    


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("head_easy类");

        System.out.println("dopost类");
//        获得cookie
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
    
    
            for(Cookie c:cookies){
    
    
                String cName = c.getName();
                String cValue = c.getValue();
                System.out.println(cName+cValue);
            }
        }
        else{
    
    

   System.out.println("cookie是空的");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("head_easy类");
        System.out.println("doget类");
        this.doPost(req,resp);
    }
}

Interpret cookies

package learn.myweb;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//使用注解可以更加简便。其中有默认参数,例如loadstarup
@WebServlet("/head_easy")
//可以更加简化,将url省略掉,使用value就可以,进一步value也不用写
public class servlet_test extends HttpServlet {
    
    


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("head_easy类");

        System.out.println("dopost类");
//        获得cookie
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
    
    
            for(Cookie c:cookies){
    
    
                String cName = c.getName();
                String cValue = c.getValue();
                System.out.println(cName+cValue);
            }
        }
        else{
    
    

   System.out.println("cookie是空的");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("head_easy类");
        System.out.println("doget类");
        this.doPost(req,resp);
    }
}

If there is a cache in the same browser, it will be empty if it is not the same
. 3. Implementation principle
* Based on response header set-cookie and request header cookie implementation
* Subject to protocol constraints, the data will be stored locally when the response header is recognized, and it will be carried in the next transmission data,
Insert picture description here

Insert picture description here

Insert picture description here
Deploy multiple web projects under one web server

Insert picture description here

Insert picture description here
4. Cookie details

  1. Can multiple cookies
    be sent at one time? *Yes
    * You can create multiple Cookie objects, and use response to call the addCookie method multiple times to send cookies.
    2. How long is the cookie stored in the browser?
    1. By default, when the browser is closed, the cookie data is destroyed, that is, the cookie exists in the browser memory at this time, and it is released when it is closed
    2. Persistent storage:
    * setMaxAge(int seconds)
    1. Positive number: set the Cookie The data is written to a file on the hard disk. Persistent storage. And specify the cookie survival time, after the time is up, the cookie file will automatically become invalid. It is still valid within 30s after closing the browser, indicating the validity period of the website login. It is convenient to log in after closing the
    cookie.setxxx(0)
    3. Negative number: default value, in memory
    4. Zero: delete cookie information, cookie is not in memory and hard disk, The server cannot directly manipulate the client computer information. By operating the client computer cookie in this way, it will be cleared within the lifetime of the
    cookie 3. Can the cookie be stored in Chinese?
    * Before tomcat 8, it is not possible to store Chinese data directly in a cookie.
    * Chinese data needs to be transcoded-generally URL encoding (%E3)
    * After tomcat 8, cookies support Chinese data. Special characters are still not supported, it is recommended to use URL encoding storage, URL decoding analysis
    4. Cookie multi-item sharing problem?
    1. Assuming that multiple web projects are deployed in a tomcat server, can cookies be shared among these web projects?
    * Cookies cannot be shared by default

     		* setPath(String path):设置cookie的获取范围。默认情况下,设置当前的虚拟目录。统一服务器的不同项目有共享数据的需求
     			* 如果要共享,则可以将path设置为"/"
    
     	
     	2. 不同的tomcat服务器间cookie共享问题?
     	3. 由于项目过大,分支过多,如果将资源部署在同一服务器上,那么服务器无法支持,因此多台服务器之间也有共享数据需求
     		* setDomain(String path):如果设置一级域名相同,那么多个服务器之间cookie可以共享
     			* setDomain(".baidu.com"),那么tieba.baidu.com和news.baidu.com中cookie可以共享
    
  2. The characteristics and functions of
    cookies 1. Cookies store data in the client browser, which is easy to tamper and lose
    . 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 )
    * Function:
    1. Cookies are generally used to store a small amount of less sensitive data
    2. To complete the server's identification of the client without logging in

  3. Case: Remember the time of the last visit
    . 1. Requirements:
    1. Visit a Servlet. If it is the first visit, you will be prompted: Hello, and welcome your first visit.
    2. If it is not the first visit, the prompt: Welcome back, the time of your last visit is: The display time string is
    realized by using cookies to determine whether the cookie with a specific name exists, if it exists, the time is taken out and the time is updated to display the back slogan. If it does not exist, it will be created and put in the time to display the welcome slogan.
    But the special characters in the cookie, such as spaces do not support display, should use urlencoder encoding for special characters

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/Test01_01")
public class Test01_01 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        System.out.println("01-01-dopostt");
//        Cookie msg = new Cookie("MSG", "hello");
//        msg.setPath("/");
//        response.addCookie(msg);
//        回复消息有中文,因此加上响应头
        response.setContentType("text/html;charset=utf-8");
//        获得所有的cookie
        Cookie[] cookies = request.getCookies();
        Boolean exit=false;
//        遍历所有的cookie,为什么要判断cookie长度
        if(cookies!=null && cookies.length>0){
    
    
            for(Cookie c:cookies){
    
    
//                如果有特定的cookie名字出现
                if(c.getName().equals("last_time")){
    
    
                    exit=true;
//                    返回上次的登录时间,为什么要使用url与解码,特殊字符?是空格一类
                    String decoded_time = URLDecoder.decode(c.getValue(), "utf-8");
                    response.getWriter().write("<h1>"+"欢迎回来"+decoded_time+"<h1>");
//                    将当前时间值更新进入cookie中
                    Date date = new Date();
//                    重新设定date显示格式,其默认为美国格式
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String formated_date = dateFormat.format(date);
//                    将当前时间编码后存储
                    String encode_date = URLEncoder.encode(formated_date, "utf-8");
                    c.setValue(encode_date);
//                    设置cookie存活时间
                    c.setMaxAge(24*60*60);
                    response.addCookie(c);

                }
                else{
    
    
//                    response.getWriter().write("有cookieda都不符合条件");

                }
//                找到就推出循环

                break;
            }
        }
//        判断需要的文件是否存在,如果不存在就创建

        if(cookies==null || cookies.length==0 || exit==false){
    
    
            //                    将当前时间值更新进入cookie中
            Date date = new Date();
//                    重新设定date显示格式,其默认为美国格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
            String formated_date = dateFormat.format(date);
//                    将当前时间编码后存储
            String encode_date = URLEncoder.encode(formated_date, "utf-8");
            Cookie c = new Cookie("last_time", encode_date);
//                    设置cookie存活时间
            c.setMaxAge(24*60*60);
            response.addCookie(c);
            response.getWriter().write("您首次登录");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("01-01-doget");
        this.doPost(request, response);
    }
}

JSP: Getting started

1. 概念:
	* Java Server Pages: java服务器端页面
		* 可以理解为:一个特殊的页面,其中既可以指定定义html标签,又可以定义java代码
		* 用于简化书写,将java与html结合在一起


2. 原理
	* JSP本质上就是一个Servlet

Insert picture description here
Configured in this folder, the index under the work becomes class, the work stores the
Insert picture description here
internal class of the resource file jsp-java-httpJspBase generated at runtime, and the -httpserverlet
service method outputs the basic html elements and encapsulates the page elements for easy invocation. It is equivalent to attaching an interpreter, so it simplifies writing
3. JSP script: JSP defines the way of Java code
1. <% code%>: the defined java code, in the service method. What can be defined in the service method, what can be defined in the script, define local variables, and have a small scope.
2. <%! Code%>: The defined java code, the member position of the java class after jsp conversion, is a type of member variable, why not write it together? Not commonly used, the scope of action is relatively large. .
3. <%= Code%>: The defined java code will be output on the page. What can be defined in the output statement, what can be defined in the script, the page output statement.

4. JSP的内置对象:
	* 在jsp页面中不需要获取和创建,可以直接使用的对象,因为这些方法后来解释的时候都会放到service中执行,service中resp,req可以识别这些方法
	* jsp一共有9个内置对象。
	* 今天学习3个:
		* request
		* response
		* out:字符输出流对象。可以将数据输出到页面上。和response.getWriter()类似
			* response.getWriter()和out.write()的区别:
				* 在tomcat服务器真正给客户端做出响应之前,会先找response缓冲区数据,再找out缓冲区数据。
				* response.getWriter()数据输出永远在out.write()之前,就是response无论定义在哪里,都输出在out之前
				* 因此建议使用out,不至于突然打乱布局,out顺序输出

Code truncation, you can write control and display in segments
Advantages: JSP can be updated in time without restarting the server

Session:

1. 概念:服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象中。HttpSession
也是域对象,类似context,一次会话
3. 快速入门:
	1. 获取HttpSession对象:
		HttpSession session = request.getSession();
	2. 使用HttpSession对象:
		Object getAttribute(String name)  
		void setAttribute(String name, Object value)
		void removeAttribute(String name)  

4. 原理
	* Session的实现是依赖于Cookie的。
	* 就是服务器创建一个session,指定唯一id,浏览器申请资源的时候将cookieID响应,反馈数据,后来浏览器访问其他资源携带这个cookieID,服务器会根据这个ID找到内部的数据,反馈,安全性高,内存消耗
  1. Details:
    1. When the client is closed, the server is not closed, is the same session obtained twice?
    * by default. It's not. When the session is over, you can print the session and print the id, different
    *
    * 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©;

     2. 客户端不关闭,服务器关闭后,两次获取的session是同一个吗?
     	* 不是同一个,但是要确保数据不丢失。tomcat自动完成以下工作,比如用户购物期间服务器重启,应当保证之前用户的数据不丢失,便于接下来的操作
     		* session的钝化:
     			* 在服务器正常关闭之前,将session对象系列化到硬盘上
     		* session的活化:
     			* 在服务器启动后,将session文件转化为内存中的session对象即可。
     		idea不活化,原因?钝化成功,将session.ser存储但是活化失败,因为当项目重启后,会将work目录删掉,导致之前的钝化无用,无法恢复数据
     		先找到本地项目-out目录(部署的项目,打包war)-找到tomcat目录下webapps,放入识别,开启(被解压)-
     		服务器开启,访问-需要是打包的名字+资源名代表实际路径,不再是虚拟路径
     		同tocmat目录下work目录运行时动态资源,比如jsp-java,session被序列化的文件也存储,这里服务器正常关闭后会将文件放入目录内,session.ser,当下次开启服务器,会自动读取session.ser,方便。
     		未来开发不在idea中部署,而是扔到webapps中居多,保证了钝化的work不会被轻易删除
     3. session什么时候被销毁?
     	1. 服务器关闭
     	2. session对象调用invalidate() 。
     	3. session默认失效时间 30分钟,这就是一些网站30分钟重新登录的原因
     	可在tomcat的conf中web.xml中修改默认配置
     		选择性配置修改	
     		<session-config>
     	        <session-timeout>30</session-timeout>
     	    </session-config>
    
    1. Features of session

      1. session is used to store the data of multiple requests for a session, and it is stored on the server side
      2. Session can store data of any type and size
      • The difference between session and cookie:
        1. Session stores data on the server side, and cookies on the client side
        2. There is no data size limit for session, cookies have
        3. The session data is safe. Compared with the insecure
          jsp , Cookie can’t be used directly in the browser. Use the server

When comparing strings for equality, the variable is empty should be considered. The best way is, str.equals, which can guarantee that it is not empty to call equals.
If all variables are variables, you can use && to first judge whether it is equal to null

The verification code logic problem should be a one-time, and it will become invalid when used up, otherwise it will cause the login check to be invalid

Guess you like

Origin blog.csdn.net/lidashent/article/details/107761208