Application of cookies and sessions

Keywords: Java Operation & Maintenance Eclipse Tomcat server

Application of content Cookie and Session


Servlet common objects

ServletConfig: static data
ServletContext: shared static data. Share dynamic data. Share file data.
HttpServletRequest
HttpServletResponse
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
response.sendRedirect("ServlectDengLu");


>>Reply management
Session > > multiple requests between the same browser and the server over a period of time are called a session,
The browser closes and the session ends.
Cookie > >: concept of
The original intention of Cookie
Cookie is a client technology. The program uses each
The user data is written to the user's respective browser in the form of cookies
Cookie

Session, class name HttpSession

Cookie concept

The original meaning of Cookie is "Cookie", which is commonly known as "Cookie"

Cookie is a client technology. The program writes each user's data to their respective browser in the form of cookie.

When users use the browser to access the server, they will go with their own data. In this way, web resources deal with the data of users.

1. A Cookie can only identify one kind of information. It contains at least one name and value identifying the information.

2. A web site can send multiple cookies to a web browser, and a browser can also store multiple cookies.

3. The browser is generally allowed to store only 300 cookies, and each website can store up to 20 cookies. The size of each cookie is limited to 4kb.

4. If a cookie is created and sent to the browser, by default it is a session level cookie (i.e. stored in the browser's memory), which will be deleted after the user exits the browser.

Session concept

HttpSession object
The server creates an HttpSession object for each session
Each session object has a unique ID
hold
The user's data is saved in the corresponding HttpSession object.

session application

package com.Servlect;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Servlet2
 * session
 */
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet2() {
        super();
        // TODO Auto-generated constructor stub
        System.out.println("session servlect2 In operation");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		//When a file browser accesses the server servlet, you need to check whether the session object of the browser has just been created
		HttpSession session=request.getSession();
		//session.isNew() determines whether the session value is empty
		if (session.isNew()) {
			//session was just created
			//The browser is the first time to access the server
			pw.print("The browser is the first time to access the server");
			//Set three dynamic data
			session.setAttribute("text1", "First class scholarship");
			session.setAttribute("name", "hug");
			session.setAttribute("pw", "12345");
			//Delete specified data
			//session.removeAttribute("text1");
			//When a large amount of data is stored in a session, if you need to destroy all of it, you can directly kill the session object
			//session.invalidate();
		}else {
			String info=(String) session.getAttribute("text1");
			String info1=(String) session.getAttribute("name");
			String info2=(String) session.getAttribute("pw");
			System.out.println("The browser is not the first time to access the file content of the server");
			System.out.println("The browser is not the name of the server for the first time");
			System.out.println("This is not the first time the browser has accessed the server's password");
			System.out.println("=====================================================");
			pw.print("<h1>The browser is not the first time to access the file content of the server<hr></h1>"+info);
			pw.print("<h1>The browser is not the name of the server for the first time<hr></h1>"+info1);
			pw.print("<h1>This is not the first time the browser has accessed the server's password<hr</h1>"+info2);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

Cookie

package com.Servlect;

import java.io.IOException;
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;

/**
 * Servlet implementation class Demo01Servlet
 */
@WebServlet("/Demo01Servlet")
public class Demo01Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Demo01Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		//Gets the content in the text box
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //First, judge whether the account and password are correct
        if("hug".equals(username) && "123".equals(password)){
            //After successful login, judge whether the user has clicked remember me
            String remember = request.getParameter("remember");
            if (remember != null) { //Because the radio box is null by default, the value is on after it is selected
                //If the user clicks, it is saved in the Cookie
                Cookie cookie = new Cookie("username",username);
                //Set access path
                cookie.setPath(request.getContextPath()+"/index.html");
                //Set lifetime
                cookie.setMaxAge(60);
                //Pass the cookie content to the browser response header
                response.addCookie(cookie);



                Cookie cookie1 = new Cookie("password",password);
                //Set access path
                cookie1.setPath(request.getContextPath()+"/login.html");
                //Set lifetime
                cookie1.setMaxAge(60 * 60 * 24);
                //Pass the cookie content to the browser response header
                response.addCookie(cookie1);
            }
            //Log in successfully and jump to the success page
            response.sendRedirect("ServlectA");
        }else{
            //Login failed, jump to failure page
        	System.out.println("Login failed,Jump to failure page");
            response.sendRedirect("ServlectB");
        }
    }

}
package com.Servlect;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServlectA
 */
@WebServlet("/ServlectA")
public class ServlectA extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServlectA() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		pw.print("<h1>Customer: congratulations on your successful login</h1>");
		
		
		
		
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
package com.Servlect;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServlectB
 */
@WebServlet("/ServlectB")
public class ServlectB extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServlectB() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		pw.print("<h1 >Customer: you successfully logged in but failed</h1>");
		response.setHeader("refresh", "10;url=Demo01Servlet");
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
    <title>User login</title>
    <!--Import js file-->
    <script src="js/commons.js"></script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>User login</h2>
<form action="Demo01Servlet" method="post" id="loginForm">
    <table>
        <tr>
            <td width="60">user name</td>
            <td><input type="text" name="username" id="username"/></td>
        </tr>
        <tr>
            <td>password</td>
            <td><input type="password" name="password" id="password"/></td>
        </tr>
        <tr>
            <td>Remember me</td>
            <!--No, value Property, its value in the point is on-->
            <td><input type="checkbox" name="remember"/></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Sign in"/></td>
        </tr>
    </table>
</form>
</body>
</html>

Operation interface

 

  Servlet common objects

ServletConfig: static data
ServletContext: shared static data. Share dynamic data. Share file data.
HttpServletRequest:
HttpServletResponse:

Cookie

Session 

HttpServlet
Request  and response
Basic knowledge of response
HttpServlet
After receiving the http request from the client, the Web server will create a request object representing the request and a response object representing the response for each request
The request and response objects represent the request and response. To obtain the data submitted by the client, we only need to find the request object. To output data to the client, we only need to find the response.
response is just an object name, HttpServletResponse class
Student   xiaoming=new Student();   Class name: Student       Object name: Xiaoming
Redirect: redirect access
Function: used to start another Servlet from one Servlet
Redirect:
Redirection belongs to the browser jump, not the server itself     Hyperlinks are the same
Redirect jump page browser address will change
Redirect to two requests
Redirection can access the page Jump of different servers
request
Function: used to receive the data information sent by the browser on the server
Request forwarding
response redirection reassigns the access direction
sendRedirect("ServletB");
Start a new servlet from a servlet
Redirection: jump belonging to browser

Difference between request forwarding and redirection:
The redirect jump browser address will change,
The request forwarding browser address will not change
Redirection is two requests, and request forwarding is one request
Redirection belongs to browser jump, and request forwarding belongs to server internal jump
The redirect jump page cannot send data,
Request forwarding can carry data

Posted by pistolfire99 on Wed, 27 Oct 2021 07:46:50 -0700