Course introduction:
1 Loading web application resource files
2 Getting started with cookies
3 Cookie details
4 Cookie case-user’s last visit Time 1
5 cookie case-user’s last visit time 2
6 cookie case-browsed products
7 session technology detailed explanation
Play address ://m.sbmmt.com/course/564.html
Lecturer characteristics: Rigorous thinking, seriousness, knowing how to grasp the key points, so that students know when to focus on memory , learn easily and learn quickly.
Difficulty analysis: Key points of cookie principles;
The similarities and differences between cookie and session;
When to use cookie and session.
Courseware download address: //m.sbmmt.com/xiazai/code/2083
Because the HTTP protocol is a stateless protocol, the WEB server Each user request is treated as a new request. However, many WEB applications require saving certain information from the last request. In order to solve this problem, the problem of session and state management
arises. In the video, relevant knowledge points include: sessions and session states in WEB applications, cookies, using cookies in Servlet programs
, Sessions, typical cases of Sessions, and persistence management of Sessions.
The so-called session refers to a series of requests and responses that occur continuously between a client browser and the WEB server. The session state of the WEB application
refers to the state information generated by the WEB server and the browser during the session. With the help of the session state, the WEB server can
belong to a series of requests in the same session. associated with the response process. For example, when a user logs in from the website's login page and then
enters the shopping page to make a purchase, the server program responsible for processing the shopping request must know the user
obtained by the program that processed the previous request. information. Since the HTTP protocol is a stateless protocol, the WEB server itself cannot identify which requests are issued by the same browser. Each request of the browser is completely isolated. Therefore, the WEB server program must be able to distinguish which request messages belong to the same session from a large number of request messages, that is, it must be able to identify access requests from the same browser, which requires the browser to issue Each
request message is identified. Request messages belonging to the same session are all accompanied by the same identification number, while request
Header field. The cookie content set in the Set-Cookie2 header field is a string with a certain format. It must start with the name of the cookie
and the set value. The format is "name=value", and can be followed by 0 or Multiple other optional attributes separated by semicolons (;) and spaces.
The attribute format is generally "attribute name = value".
Finally, let’s explain the request header field of the cookie returned by the browser. The browser uses the Cookie request header field to send the Cookie information back to the WEB server. Multiple cookie information is sent back to the WEB server through a Cookie request header field. Whether the browser sends a certain
Cookie information is determined according to the following rules:
1. Whether the requested host name matches the Domain attribute of a stored cookie
2. Whether the requested port number is in the Port attribute list of the Cookie
3. Whether the requested resource path is in the directory and subdirectory specified by the Path attribute of the Cookie
4. Whether the validity period of the cookie has expired. Each cookie in the Cookie request header field is separated by a comma (,) or semicolon (;)
. In addition to the "name = value" setting, the Cookie request header field can also have several attributes such as Version, Path, Domain, Port
, etc. However, if you want to set attributes such as Version, Path, Domain, Port, etc., you need to add a
"$" character as a prefix before the attribute name, and the Version attribute can only appear once and must be located in the Cookie request header field. At the front of the setting value,
If you need to set the Path, Domain, Port and other attributes of a certain cookie information, they must be located after the "name=
value" setting of the cookie information. It should be noted that the Path attribute points to the cookie in the subdirectory before the
Cookie that the Path attribute points to the parent directory. For example: Cookie: $Version=1; Course=Java; $Path=/it315/lesson; Course=vc;
$Path=/it315. This cookie complies with the above constraints. A specific example is demonstrated in the video tutorial:
代码一: Cookie ckName = new Cookie("name",name); Cookie ckNickname = new Cookie("nickname",nickname); ckNickname.setMaxAge(365*24*3600); Cookie ckEmail = new Cookie("email","test1@it315.org"); Cookie ckPhone = new Cookie("phone","1111111"); response.addCookie(ckName); response.addCookie(ckNickname); response.addCookie(ckEmail); response.addCookie(ckPhone);
代码二: String lastNickname = null; Cookie [] cks = request.getCookies(); for(int i=0; cks!=null && i<cks.length; i++) { if("nickname".equals(cks[i].getName())) { lastNickname = cks[i].getValue(); break; } } if(lastNickname != null) { out.println("欢迎您," + lastNickname ); }
The above code snippet generates four cookie information named name, nickname, email, and phone. The values of the two cookies name and
nickname are set through request parameters, and the cookie nickname remains valid for 1
year. The values of the two cookies email and phone It is specified hard-coded in the program. The second code snippet is to generate the Cookie information
and then search for the Cookie information named nickname from the request message, and print out the corresponding greeting based on the returned result. The
fragment also prints The value of the Cookie header field in the outgoing request message.
Understand the concept of session and Cookie technology, and then give a detailed introduction and example demonstration of Session. This video mainly explains
What is Session, Session tracking mechanism, Session timeout management, methods in the HttpSession interface,
Session methods in the HttpServletRequest interface, application and session domain scope Attribute comparison, using
Cookie to implement Session tracking, and using URL rewriting to implement Session tracking. These technologies will be used frequently in the future.
Using cookies and additional URL parameters can pass the status information of the previous request to the next request. However, if more status information is passed, it will greatly reduce the network transmission efficiency. And increase the difficulty of server-side program processing. In order to solve this problem,
Session technology was born. Session technology is a technology that saves session state on the server side. During the session, the client needs to receive, remember, and send back the session ID number of the Session. Session can and usually uses Cookie to pass the session ID number. As you can see, Cookie and Session often work together, which can solve the stateless nature of the HTTP protocol
. With the concept of Session, a program is needed to implement it, and then allow the server to successfully track a specific Session.
In the Servlet API specification, an HttpSession interface is defined. The HttpSession interface defines various methods for managing and operating session
session status. The HttpSession object generated by the WEB server is a storage structure that maintains session state information. A client corresponds to a respective HttpSession object on the
WEB server. The WEB server does not create a
HttpSession object when the client starts to access it. The WEB application will create
# only when the client accesses a Servlet program that can open a session with the client. ##Create an HttpSession object corresponding to the client. The WEB server assigns a unique session identification number to each HttpSession object, and then passes this session identification number to the client in the response message. The client needs to remember the session identification number and transmit this session identification number to the WEB server in each subsequent access request. The WEB server program relies on the returned session identification number## The # sign will tell you which client issued this request, so you can select the corresponding HttpSession object. Because the server-side resources are limited and cannot save HttpSession objects without limit, the WEB application creates a
corresponding to a certain client.HttpSession对象后,只要没有超出一个限定的空闲时间段,HttpSession对象就驻留在WEB服务器内
存之中,该客户端此后访问任意的Servlet程序时,它们都使用与客户端对应的那个已存在的
HttpSession对象。HttpSession接口中专门定义了一个setAttribute方法来将对象存储到
HttpSession对象中,还定义了一个getAttribute方法来检索存储在HttpSession对象中的对象,存
储进HttpSession对象中的对象可以被属于同一个会话的各个请求的处理程序共享。
前面提到的服务器资源有限,WEB服务器无法判断当前的客户端浏览器是否还会继续访问,也无
法检测客户端浏览器是否关闭,所以,即使客户已经离开或关闭了浏览器,WEB服务器还要保留与之
对应的HttpSession对象。但是随着时间的推移而不断增加新的访问客户端,WEB服务器内存中将会
因此积累起大量的不再被使用的HttpSession对象,并将最终导致服务器内存耗尽。因此WEB服务器
采用“超时限制”的办法来判断客户端是否还在继续访问,如果某个客户端在一定的时间之内没有发
出后续请求,WEB服务器则认为客户端已经停止了活动,结束与该客户端的会话并将与之对应的
HttpSession对象变成垃圾。如果客户端浏览器超时后再次发出访问请求,WEB服务器则认为这是一
个新的会话的开始,将为之创建新的HttpSession对象和分配新的会话标识号。虽然会有少数出现事
实上的同一会话,却产生两次HttpSession对象,但是相对于大量正常的访问请求,这种情况基本上
可以忽略了。在Servlet API中,会话的超时间隔可以在web.xml文件中设置,其默认值由Servlet容
器定义。
例如:<session-config> <session-timeout>30</session-timeout> </session-config>
下面拿出视频中的一个小例子来说明一下使用Session实现购物车:
String courseSelect = request.getParameter("course"); if(courseSelect != null){ Vector vCourses = (Vector)session.getAttribute("courses"); if(vCourses == null){ vCourses = new Vector(); vCourses.add(courseSelect); session.setAttribute("courses",vCourses); } else{ if(vCourses.contains(courseSelect)){ out.println(sessionName + ",你以前选择过了" + courseSelect + "<hr>"); } else{ vCourses.add(courseSelect); } } }
上面的代码首先判断访问请求是否来自一个已登录用户,如果不是,则将请求重定向到logon.html页
面。接着判断当前访问请求是否是用户选择课程时发出的,如果是,则将用户选择的课程加入购物车
。最后显示出所有供选择的课程列表和已放入购物车中的课程列表。
The above is the detailed content of Chuanzhi Podcast Session Management Tutorial. For more information, please follow other related articles on the PHP Chinese website!