java web Chapter 5 day 6 2020080605018

Keywords: Java Front-end

Chapter six: conversation and its conversation technology

1, Learn to master the overview of cookie objects and make

2, Master the Session object

3, HttpSession APL

4, Using URL rewriting to realize Session tracking

5, Summary

1, Foreword

1. Session overview:

In daily life, the series of questions and answers you ask me from dialing to hanging up is a conversation.
The session process in web application is similar to the process of making phone calls in life. It refers to a series of requests and responses between web servers.

1, Cookie object

1.1 Cookie overview: similar to the membership card handled in the mall, you can use this card to identify your user information and record your consumption every time you go to the mall. In this way, when the browser accesses the server again, it will send the Cookie to the server in the request header to facilitate the server to make a correct response to the browser.
When the service sends cookies to the client, the set Cookie response field will be added to the HTTP response field.
The Cookie set in the set Cookie header field follows a certain syntax format. Specific examples are as follows:
Set-Cookie: user=itcast; path=/ ;
user represents the name of the Cookie, itcast represents the value of the Cookie, and Path represents the properties of the Cookie.
1.2 why cookies
The HTTP protocol is stateless. For requests sent by a browser, the server cannot distinguish whether they are from the same source, and cannot know what the user did last time. Therefore, additional data is required to maintain the session. A Cookie is such an extra piece of data that is passed along with the HTTP request to maintain the session between the browser and the server.
1.3Cookie API:
In order to encapsulate cookie information, a javax. Serttp. Cookie class is provided in the Serlet API, which contains methods for generating cookie information and extracting various attributes of cookie information. The construction method and common methods of cookies are specific

  1. Construction method: the Cookie class has only - one construction method. The specific syntax format is as follows.

public Cookie (java.lang.String name, java.lang .String value)

In the Cookie construction method, the parameter name is used to specify the name of the Cookie, and value is used to specify the value of the Cookie. It should be noted that once a Cookie is created, its name cannot be changed. The value of the Cookie can be any value and can be modified after creation.
[task 5-1] display the last access time of the user

==2. Common methods:
1.)setMaxAge (int expiry) and getMaxAge() methods
2.)setPath (String uri) and getPath() methods
3)setDomian (string patten) and getDomain() methods==

3. Task 5-1 displays the last access time of the user

[mission objective]:

When a user accesses some Web applications, the last access time of the user is often displayed. For example, after QQ login is successful, the last login time of the user will be displayed. Through this task, readers will learn how to use Cookie technology to display the last access time of users.
[implementation steps]
1. Create a Servlet
Create a new Web project chapter05 in Eclipse, and create - a package named cn.itcast.chapter05.cookie.example under the project. Write a Servlet class named LastAccessServlet in the package. This class is mainly used to obtain Cookie information and send the current time to the client as a Cookie value. The specific implementation code of LastAccessServlet class is as follows.
** LastAccessServletjava**

package cn.itcast.chapter05.cookie;
import java.io.IOException;
import java.util.Date;
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 LastAcess
/
@WebServlet("/last")
public class LastAcess extends HttpServlet {
private static final long serialVersionUID = 1L;
/*
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies=request.getCookies();

String lasttime=null;
for(int i=0;cookies!=null&&i<cookies.length;i++) {
String name=cookies[i].getName();
if("lastAccess".equals(name)) {
lasttime=cookies[i].getValue();
}
}
if(lasttime==null) {
response.getWriter().print("This is your first visit to this website ");
}else {
response.getWriter().print("When was your first visit:"+lasttime);

 }
1
String time = String.format("%tF%<tT", new Date());
Cookie cookie= new Cookie("lastAccess",time);
Cookie cookie2=new Cookie("lastAccess","123");
response.addCookie(cookie);
response.addCookie(cookie2);
}
/**

@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);
}
}
example
package cn.itcast.chapter05.session;
import java.io.IOException;
import java.util.Date;
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 example
/
@WebServlet("/example")
public class example extends HttpServlet {
private static final long serialVersionUID = 1L;
/*
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String time = String.format("%tF%<tT", new Date());
Cookie cookie= new Cookie("lastAccess",time);
Cookie cookie2=new Cookie("lastAccess","123");
response.addCookie(cookie);
response.addCookie(cookie2);
}
/*
@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);
}
}*

2, Session object

Cookie technology can save users' information in their respective browsers, and can realize data sharing under multiple requests. However, if more information is transmitted, using cookie technology will obviously increase the difficulty of server-side program processing. At this time, session technology can be used. Session is a technology that saves session data to the server. Next, this section will explain session in detail.

3, HttpSession Apl

Session is closely related to each request message. Therefore, HttpServletRequest defines the getSession() method used to obtain the session object. This method has the following two overload methods

public HttpSession getSession(boolean create)
public HttpSession getSession()

Always create a new HttpSession object when the related HttpSession object does not exist. Here is a special thing to note: because the getSession method may generate the Cookie field header for sending the session mark number, you must call the getSession() method before sending any response content.

2.1 Session timeout management

session mechanism is a server-side mechanism. The server uses a structure similar to hash table (that is, hash table) to save information.
When the program needs to create a session for a client's request, the server first checks whether the client's request contains a session id - called session id. if a session id is included, it indicates that a session has been created for the client before, and the server retrieves the session according to the session id (if it cannot be retrieved, a new one may be created) , if the client request does not contain a session id, create a session for this client and generate a session id associated with this session. The value of the session id should be a string that will not be repeated and is not easy to find rules to copy. This session id will be returned to the client for saving in this response.

Save this session id The method can be adopted cookie,In this way, the browser can automatically display this ID to the server according to the rules during the interaction cookie Their names are similar to SEEESIONID,And... For example weblogic about web Application generated cookie. 

There is no difference between the two methods for users, but the server processes them differently during parsing. The first method is also helpful to distinguish the session id information from the normal program parameters.
In order to maintain the state throughout the interaction, the session id must be included after the path that each client may request.

Another technology is called form hidden field. That is, the server will automatically modify the form and add a hidden field so that the session id can be passed back to the server when the form is submitted.
For example, the following form:

  <form name="testform" action="/xxx"> 
<input type="text"> 
</form> 

Before being passed to the client, it will be rewritten as: 

<form name="testform" action="/xxx"> 
<input type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764"> 
<input type="text"> 
</form> 

This technology has been less applied now, and the author has been in contact with very old technology iPlanet6(SunONE Predecessor of application server)This technology is used. 

In fact, this technology can be simply replaced by applying URL rewriting to action.

2.2 [task 5-2 realize shopping cart]

Task objective: to create an encapsulated book information class

Create a new package named cn.itcast.chapter05. Session.example01 under chapter05 project, and create a class named Book in the package. This class is used to encapsulate the information of books, in which the id and name attributes are defined to represent the number and name of books respectively.
Implementation steps:

1. java class of book

Book.java

public Book(String id, String name) {

	this.id = id;
	this.name = name;
}
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;
}**

data = pd.read_csv(
    'https://labfile.oss.aliyuncs.com/courses/1283/adult.data.csv')
print(data.head())

2. The database simulates the java class of BookDB

Create database simulation class
cn.itcast.chapter05. session.example01 create a database named BookDB to store all books.
BookDB.java


package cn.itcast.chapter05.session;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class BookDB {
private static Map<String,Book> map = new LinkedHashMap<String,Book>();
static{
map.put("1", new Book("1","javaWeb"));
map.put("2", new Book("2","jdbc Getting started));
map.put("3", new Book("3","java "Foundation"));
map.put("4", new Book("4","struts Frame "));
map.put("5", new Book("5","hibernate Frame "));

}
//1. Get all books
public static Collection<Book> getAll(){
	return map.values();
}
//2. Get a book according to the key of the map, that is, the id of the book
public static Book getBook(String id){
	return map.get(id);
}

3. Create a Servlet

1. Create a Servlet class named ListBookServlet, which is used to display the list of all available books. Click the "buy" link to add the specified books to the shopping cart. Its implementation code is as follows.
Servlet class of ListBookServlet

package cn.itcast.chapter05.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

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 ListBookServlet
 */
@WebServlet("/list")
public class ListBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @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());
		response.setContentType("text/html;charset=utf-8");
		Cookie[] cookies =request.getCookies();
		
		Collection<Book> books=BookDB.getAll();
		
		PrintWriter out = response.getWriter();
		out.print("The books sold on this website are as follows:");
		
		for(Book b:books) {
			String name= b.getName();
			String id=b.getId();
			String url="<a href='purcharse?id="+id+"'>Click buy</a>";
			out.print("Book Name:"+name+" "+url+"<br/><br/>");			
		}
	}

	/**
	 * @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);
	}

}

2. Create a Servlet class named PurchaseServlet and its implementation code.
Servlet class of PurchaseServlet

package cn.itcast.chapter05.session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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 javax.servlet.http.HttpSession;

/**
 * Servlet implementation class PucharseServlet
 */
@WebServlet("/purcharse")
public class PucharseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PucharseServlet() {
        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());
		response.setContentType("text/html;charset=utf-8");
		String id=request.getParameter("id");
		if(id==null){
			response.sendRedirect("/chapter05/list");
			return;
		}
		Book book =BookDB.getBook(id);
		
		HttpSession session=request.getSession();
		
		List<Book> list=(List<Book>) session.getAttribute("cart");
		if(list==null) {
			list=new ArrayList<Book>();
			session.setAttribute("cart", list);
		}
		
		list.add(book);
		
		Cookie cookie = new Cookie("JESSIONID", session.getId());
		response.addCookie(cookie);
		response.sendRedirect("/chapter05/cart");
	}

	/**
	 * @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);
	}

}

The above two functions are realized: one is to save the book information purchased by the user to the Session object; the other is to redirect the page to the list of books purchased by the user after the user purchases the books. When this class is implemented, it simulates a shopping cart through the ArrayList collection, then adds all the purchased books to the shopping cart, and finally passes them to the CartServlet through the Session object. The CartServlet displays the books that the user has purchased.
3. Create a Servlet class named CartServlet, which is mainly used to display the list of books purchased by users and its implementation code.

Servlet class of CartServlet

package cn.itcast.chapter05.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 CartServlet
 */
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @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());
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		List<Book> cart=null;
		HttpSession session = request.getSession(false);
		boolean cartflag=false;
		if(session==null) {
			cartflag=false;
		}else {
			cart=(List<Book>)session.getAttribute("cart");
			if(cart==null) {
				cartflag=false;
			}
		}
		if(!cartflag) {
			out.print("Sorry, please go to buy books");
		}else {
			
			out.print("Books purchased are as follows:"+"<br/>");
			for(Book b:cart) {
				out.print("Purchase books:"+b.getName()+"<br/>");
			}
		}
		
		
	}

	/**
	 * @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);
	}

}


4. Run the project and view the results

Configure the corresponding Servlet in web.xml, then start the Tomcat server and enter the address in the browser http://ocalhost:9999/chapter05/ListBookServlet ”Access listbookservlet, and the browser displays the following results:

So far, the shopping cart program using Session is completed. Note: to save the Session ID attribute, you need to create a Cookie object and set the effective time of the Cookie. The advantage of this is that within a certain period of time, even if the user closes the browser and reopens the browser page, the server can find the Session object previously created for the user.

4, Using URL rewriting to realize Session tracking

As mentioned earlier, when the server passes the ID attribute of the Session object, it transmits it to the browser in the form of a Cookie.
**1.url rewriting principle: * * when the server program calls request.getSession(); When coding, it will first see whether there is a cookie named JSESSIONID in the request.getCookies() method. If not, it will see whether the URL has been rewritten (i.e. with JSESSIONID). If so, find the session object with key JSESSIONID from the server. If not, create a new session. If the user disables cookies, session tracking can only be realized through URL rewriting!
1.1 URL rewriting in Servlet:

After accessing this Servlet, the client will return to the main page:

package edu.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class EncodeURL extends HttpServlet {
 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        request.getSession();  //Create session
        //Calling the encodeURL method of response will automatically append JSESSION to the url, such as url;jsessionid=BD111FFC653497E81B702A29B3AC6FE4
        String buyurl = response.encodeURL("/CookieAndSession/servlet/buy");
        String payurl = response.encodeURL("/CookieAndSession/servlet/pay");
        out.print("<a href='"+buyurl+"'>purchase</a><br/>");
        out.print("<a href='"+payurl+"'>Check out</a><br/>");
        
	}
 
}

1.2: disable browser cookies.

Click the OK button in the figure. At this time, all cookies in the browser are disabled.
1.3: refresh or re access the address“ http://localhost:8080/chapter05/CarServle ”At this time, it is found that the browser displays the results as shown in the following figure:


Special * attention here:

1. However, if the user disables cookies, and then closes the browser and reopens the browser, the reply will be invalid and the reply tracking cannot be realized; If the user does not disable the cookie, you can control that the session does not expire after the browser is closed by setting the expiration time of the cookie loaded with JSESSIONID.

==2. If the user does not disable cookies and uses URL rewriting, when accessing the EncodeURLServlet for the first time, the user does not know whether the user has disabled cookies, so the JSESSIONID will be rewritten on the URL inside the response.encodeURL() method. However, when accessing the EncodeURLServlet for the second time, because the user comes with a cookie, the response.encodeURL() JSESSIONID will not be rewritten on the URL===

5, Summary:

This chapter mainly explains the relevant knowledge of cookie object and session object. Cookie is the earliest session tracking technology, which saves information to the client browser. The browser will carry these cookies when visiting the website, which saves the information on the server side. Session can store complex Java objects, so it is more convenient to use.

Posted by damianjames on Sun, 21 Nov 2021 00:51:31 -0800