Servlet from entry to soil-session technology Cookie and Session

Servlet

Through this blog, you will learn the following knowledge: Servlet session technology, mainly explaining how to use Cookie and Session and the difference between them

Conversation technology

  • The user opens a browser and visits a website, as long as the browser is not closed, no matter how many hyperlinks the user clicks, how many resources are accessed, until the user closes the browser, the whole process is called a session

Cookie

  • User's pass to access the server
  • Process: The browser accesses the server. If the server needs to record the user's status, it will use the response to send a cookie to the browser, and the browser will save the cookie. When the browser visits the server again, the browser will pass the requested URL to the server together with the cookie
  • Recognizing the returning user includes three steps
    • The server script sends a set of cookies to the browser.
    • The browser stores this information on the local computer
    • The next time the browser sends any request to the Web server, the browser will send these cookie information to the server, and the server will use the information to identify the user.

Set cookies through servlet

  • Create a Cookie object
Cookie cookie = new Cookie("key","value");
  • Set the maximum lifetime: in seconds
cookie.setMaxAge(60*60*24); 
  • Send Cookie to Http response header:
response.addCookie(cookie);

Cookie details

  • Non-cross-domain
  • Validity period: set by MaxAge, the default value is -1
    • Positive number: indicates the survival time, stored in the hard disk, whether it is closed the browser or the computer is valid
    • Negative number: indicates that the cookie is temporary, only valid in this browser, and it will be invalid when it is closed.
    • 0: means delete the cookie
  • Modify and delete
    • Delete: Control by MaxAge=0
    • Modification: Cookie storage is similar to Map, only the key is unchanged and the value is changed.
  • Domain name: The domain attribute determines the domain name used to access the cookie
  • Path: path attribute
  • Security attribute: Set the secure attribute to true, and the browser will only transmit the cookie in secure protocols such as HTTPS and SSL

Cookie application

  • Show the time the user last visited:

    First check all cookies to see if they are needed, if not, it is the first login

            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter printWriter=response.getWriter();
            //获取页面上所有的Cookie
            Cookie[] cookies=request.getCookies();
            //判断Cookie的值是否为空
            String cookieValue=null;
            for(int i=0;cookies!=null&&i<cookies.length;i++){
          
          
                //获取以time命名的Cookie,同时避免空指针异常
                if("time".equals(cookies[i].getName())){
          
          
                    printWriter.write("上次登录的时间是:");
                    cookieValue=cookies[i].getValue();
                    printWriter.write(cookieValue);
                    cookies[i].setValue(simpleDateFormat.format(new Date()));
                    response.addCookie(cookies[i]);
                    break;
                }
            }
            //如果Cookie为空代表第一次访问
            if(cookieValue==null){
          
          
                Cookie cookie=new Cookie("time",simpleDateFormat.format(new Date()));
                cookie.setMaxAge(20000);
                response.addCookie(cookie);
                printWriter.write("第一次访问!");
            }
    

    PS; a problem easily

Insert picture description here

Due to the higher version of Tomcat, spaces cannot be used in addCookie and 32 corresponds to spaces in ASCII code. Just delete the spaces in the code behind. So at time, just change the space to

Session

  • It is a mechanism for recording the state of the browser in a chapter. Cookies are stored in the browser and Session is stored in the server. When the user uses the browser to access the server, the server records the user information in the server in some form, which is the Session
    • Cookie is to check the user's pass to confirm the user's identity
    • Session confirms the user's identity by checking the client list on the server
  • Session can store objects, and Cookie can only store strings
  • Session relies on cookies to identify different users, but if cookies are disabled, URL rewriting should be used to solve

Session as a domain object

  • As a mechanism to record the state of the browser, as long as the Session object is not destroyed, Servlets can communicate through the Session object.

    • Set the properties of Session in the first Servlet

      //获取Session对象
      HttpSession httpSession=request.getSession();
      //设置Session属性
      httpSession.setAttribute("name","看完记得点赞");
      
    • Get in the second Servlet

      //获取Session
      HttpSession httpSession=request.getSession();
      String value=(String)httpSession.getAttribute("name");
      PrintWriter printWriter=response.getWriter();
      printWriter.write(value);
      
  • Generally speaking, when we want to save user-level data (as long as the browser is not closed and hope that the data still exists, use Session to save) data use Session.

Life cycle and validity period

  • Session is automatically created when the user accesses server Servlet, jsp and other dynamic resources for the first time, and Session is stored in memory

  • If you access static resources such as HTML, IMAGE, etc. Session will not be created

  • After the session is generated, as long as the user continues to access, the server will update the last access time of the session, regardless of whether the session is read or written, the server will think that the session is active once

  • Session has a default timeout period of 30 minutes, which can be modified

    • Set in tomcat/conf/web.xml, for all WEB applications

      <session-config>          
      	<session-timeout>20</session-timeout>       
      </session-config>
      
    • Configure in a single web.xml, valid for a single web, subject to this question

    • Set by the setMaxInactiveInterval() method (in seconds)

      //设置Session最长超时时间为60秒,这里的单位是秒
      httpSession.setMaxInactiveInterval(60);
      System.out.println(httpSession.getMaxInactiveInterval());
      

    The validity period of the Session is different from that of the Cookie

    • session
      • The period refers to the inactive time, and the time will be re-timed after the visit within the time.
      • Restart the tomcat or reload web application, or shut down the session, the session will also fail
      • Invalidate all attributes in the session through the invalidate() method (usually used for safe exit)
      • Hope that a certain data is invalid can use removeAttribute ()
    • Cookie life cycle is calculated according to the accumulated time

Use Session to prevent repeated forms submission

  • Happening:

    • Refresh in the servlet that processes the form
    • Back on submission
    • Network delay, multiple clicks on the submit button
  • solve

    • Processing form refresh in servlet

    • Back and submit

    • Network delay

      • Use JS to prevent: after the user clicks the submit button for the first time, the data is submitted to the server, when the user clicks again, the data is not submitted to the server

      • Monitor user submission events

        <%@page contentType="text/html;charset=UTF-8"language="java"%>
        <html>
        <head>    
        	<title>表单提交</title> 
        	<script type="text/javascript">       
        		//定义一个全局标识量:是否已经提交过表单数据       
        		var isCommitted =false;
        		functiondoSubmit(){
                  
                          
        			//false表示的是没有提交过,于是就可以让表单提交给Servlet        
        			if(isCommitted==false) {
                  
                  
                        isCommitted = true;           
        				return true;
        			}else{
                  
                  
                      	return false;            
                    }
                }
        	</script>
        </head>
        <body>
        <formaction="/ouzicheng/Servlet7" onsubmit="returndoSubmit()">
            用户名:<input type="text" name="username">  
        	<inputtype="submit"value="提交">
        </form>
        </body>
        </html>
        

One-time check code

  • Prevent brute force guessing
  • Verification principle: After the verification code is generated, the data of the verification code is stored in the Session domain object, and it is judged whether the user input verification code is consistent with the data of the Session domain object

achieve:

  • Generate verification code image:

    @WebServlet("/Demo")
    public class Demo extends HttpServlet {
          
          
        public Demo(){
          
          
            super();
        }
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
          
          
            //在内存中生成图片
            BufferedImage bufferedImage=new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
            //获取这张图片
            Graphics2D graphics2D=(Graphics2D) bufferedImage.getGraphics();
            //设置背景色为白色
            graphics2D.setColor(Color.white);
            graphics2D.fillRect(0,0,80,20);
            //设置图片的字体和颜色
            graphics2D.setFont(new Font(null,Font.BOLD,20));
            graphics2D.setColor(Color.BLUE);
            //生成随机数
            String randomNum=makeNum();
            //往这张图片上写数据
            graphics2D.drawString(randomNum,0,20);
            //将随机数存入Session
            request.getSession().setAttribute("randomNum",randomNum);
            //控制浏览器不缓存这张照片
            response.setHeader("Expires","-1");
            response.setHeader("Cache-Control","no-cache");
            response.setHeader("Pragma","no-cache");
            //通知浏览器以图片的方式打开
            response.setHeader("Content-type","image/jpeg");
            //把图片写给浏览器
            ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
    
        }
        @Override
        protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
          
          
            doGet(request,response);
        }
        private String makeNum(){
          
          
            Random random=new Random();
            int num=random.nextInt(999999);
            //验证码的位数要六位,于是将随机数转化为字符串,并且添加不够的位数
            String randomNum=String.valueOf(num);
            //使用StringBuffer来拼接字符串
            StringBuffer stringBuffer=new StringBuffer();
            for(int i=0;i<6-randomNum.length();i++){
          
          
                stringBuffer.append("0");
            }
            return stringBuffer.append(randomNum).toString();
        }
    }
    
  • jsp display page

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>冢狐</title>
    </head>
    <body>
    <form action="Demo1" >
      用户名:<input type="text" name="username"><br>
      密码:<input type="password" name="password"><br>
      验证码:<input type="text" name="randomNum"><br>
      <img src="/web/Demo"><br><br>
      <input type="submit"value="提交">
    </form>
    </body>
    </html>
    
  • Verify Servlet

    @WebServlet("/Demo1")
    public class Demo1 extends HttpServlet {
          
          
        public Demo1(){
          
          
            super();
        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
    
    
        }
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
          
          String clint_randomNum = request.getParameter("randomNum");
          String session_randomNum = (String)request.getSession().getAttribute("randomNum");
          PrintWriter printWriter=response.getWriter();
          printWriter.write("输入的"+clint_randomNum);
          printWriter.write("存的"+session_randomNum);
        }
    }
    
    

The difference between session and cookie

  • Storage method:
    • Cookie can only store character strings, if you want to store non-ASCII character strings, you must encode them.
    • Session can store any type of data, and Session can be regarded as a container
  • Privacy and security
    • Cookies are stored in the browser and are visible to the client . Information is easy to leak out. If cookies are used, it is best to encrypt cookies
    • Session is stored on the server and is transparent to the client . There is no leakage of sensitive information.
  • Validity period
    • Cookies are stored in the hard disk, only need to set the maxAge attribute to a relatively large positive integer, even if the browser is closed, the cookie still exists
    • The Session is stored in the server, and the maxInactiveInterval attribute value is set to determine the validity period of the Session. And the Session relies on the Cookie named JSESSIONID, the default maxAge attribute of the Cookie is -1. If the browser is closed, the Session does not die from the server, but it also becomes invalid.
  • Burden on the server
    • The session is stored on the server, and each user generates a session. If there are many concurrent users, the session cannot be used, and the session consumes a lot of memory.
    • Cookies are stored on the client. Does not occupy server resources. Large websites like baidu and Sina generally use cookies for session tracking.
  • Compare from browser support
    • If the browser disables cookies, then cookies are useless!
    • If cookies are disabled in the browser, Session can track the session through URL address rewriting.
  • From cross-domain
    • Cookie can set the domain attribute to achieve cross domain name
    • Session is only valid within the current domain name, domain name cannot be praised

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/107656357