HttpSession Basics

HttpSession

  • In WEB development, the server can create a session object (session object) for each user browser. Note: a browser has one session object (by default). Therefore, when the user data needs to be saved, the server program can write the user data to the exclusive session of the user's browser. When the user accesses other programs using the browser, other programs can take the user's data from the user's session to serve the user.
  • The main differences between Session and Cookie are as follows:
    • Cookie is to write the user's data to the user's browser.
    • session technology writes user data to user exclusive session
    • cookie client technology, can only store strings. HttpSession server-side technology, which can store objects.

Common methods of HttpSession

Save the data in the HttpSession object, which is also a domain object.
void setAttribute(String name,Object value);
Object getAttribute(String name);
void removeAttribute(String name);
HttpSession.getId():
Setmaxinactive interval (int interval) sets the session lifetime
invalidate() invalidates this session
Example demonstration (simple implementation of shopping cart):
Session1.java (purchase page)

public class Session1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//Get the book by id
		String id = request.getParameter("id");
		Book book = DBUtil.findBookById(id);
		//Get the session object
		 HttpSession session = request.getSession();
		//Remove the list from the session
		List<Book> list = (List<Book>)session.getAttribute("cart");
		if(list==null){
			list = new ArrayList<Book>();
		}
		list.add(book);//list will not store duplicate data
		
		session.setAttribute("cart", list);//Put the list back in the session domain
		
		out.print("Purchase succeeded!");
		String url = request.getContextPath()+"/servlet/session2";
		response.setHeader("refresh", "2;url="+response.encodeURL(url));
	}

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

}

Session2.java (home page)

public class Session2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Set encoding
		response.setContentType("text/html;charset=UTF-8");
		//Add output stream
		PrintWriter out = response.getWriter();
		//Get Session
		request.getSession();
		out.print("This website has the following good books:<br/>");
		Map<String, Book> books = DBUtil.findAllBooks();
		for (Map.Entry<String, Book> book : books.entrySet()) {
			String url = request.getContextPath()+"/servlet/session1?id="+book.getKey();
			out.print("<a href='"+response.encodeURL(url)+"' >"+book.getValue().getName()+"</a><br/>");
		}
		String url2 = request.getContextPath()+"/servlet/session3";
		out.print("<a href='"+response.encodeURL(url2)+"'>View Cart</a>");
	}

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

}

Session3.java (shopping cart page)

public class Session3 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print("The shopping cart has the following items:<br/>");
		 HttpSession session = request.getSession();
		//Get the session object
		List<Book> books = (List<Book>)session.getAttribute("cart");
		if(books==null){
			out.print("You haven't bought anything yet");
			//Return in 2 seconds
			response.setHeader("refresh", "2;url="+request.getContextPath()+"/servlet/showAllBooksServlet");
			//response.sendRedirect(request.getContextPath()+"/servlet/showAllBooksServlet");
			return;
		}
		for (Book book : books) {
			out.write(book.getName()+"<br/>");
			
		}
		//Set survival time
		session.setMaxInactiveInterval(60*5);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}

Entity class:
Book.java

public class Book {
	private String id;
	private String name;
	private double price;
	private String author;
	
	
	public Book(String id, String name, double price, String author) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.author = author;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price
				+ ", author=" + author + "]";
	}
	
	
}

DBUtil.java

public class DBUtil {
	private static Map<String, Book> books = new HashMap<String, Book>();
	
	static{
		books.put("1", new Book("1", "The Plum in the Golden Vase", 20, "Wang Xin Xin"));
		books.put("2", new Book("2", "Sunflower collection", 20, "Cheng Yi Yang"));
		books.put("3", new Book("3", "Jiu Yin Zhen Jing", 30, "Chen Guang"));
		books.put("4", new Book("4", "Jade girl's heart meridian", 10, "Chen Zhi Jia"));
	}
	
	//Get all the books
	public static Map<String, Book> findAllBooks(){
		return books;
	}
	
	/**
	 * Find the specified book by id
	 * @param id
	 * @return
	 */
	public static Book findBookById(String id){
		return books.get(id);
	}
}

The principle of getSession()

HttpSession request.getSession(): internal execution principle

  • 1 gets the value of the cookie named JSESSIONID.
  • 2. Without such a cookie, create a new HttpSession object, assign a unique session ID, and write a cookie named JSESSIONID=sessionID to the client
  • 3. Get the value of the cookie (that is, the value of the HttpSession object), and find the HttpSession object from the memory of the server according to its ID:
    • Found: take it out and continue to serve you.
    • Not found: starting from 2.
  • 4 HttpSession request.getSession(boolean create):
    Parameters:
    true: same function as getSession().
    false: find the corresponding HttpSession object according to the cookie value of the client JSESSIONID, and return null (no new will be created, just query).
Published 10 original articles, won praise 12, visited 1292
Private letter follow

Tags: Session Java Web Development encoding

Posted on Thu, 12 Mar 2020 01:56:25 -0400 by omelin