The principle and difference between cookie mechanism and session mechanism

1. The difference between the cookie mechanism and the session mechanism Specifically, the cookie mechanism adopts the scheme of maintaining state on the client side, while the session mechanism adopts the scheme of maintaining the status on the server side. At the same time, we also see that since the solution of maintaining state on the server side also needs to save an identifier on the client side, the session mechanism may need to rely on the cookie mechanism to achieve the purpose of saving the identifier, but there are actually other options.

Second, the difference between session cookie and persistent cookie If the expiration time is not set, it means that the cookie life cycle is during the browser session, as long as the browser window is closed, the cookie will disappear. This type of cookie that lasts for the browsing session is called a session cookie. Session cookies are generally not stored on hard disk but in memory. If an expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again after closing, and these cookies will remain valid until the set expiration time expires. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different handling methods.

Third, how to use to achieve automatic login When a user registers on a website, he will receive a cookie with a unique user ID. When the client reconnects later, this user ID is automatically returned, and the server checks it to see if it is a registered user with automatic login selected, allowing the user to access resources on the server without giving an explicit username and password .

4. How to customize the site according to the user's hobby The website can use cookies to record the user's wishes. For simple settings, the website can directly store the page's settings in a cookie to complete the customization. For more complex customizations, however, the website simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.

Five, cookie sending 1. Create a cookie object 2. Set the maximum time limit 3. Put the cookie into the HTTP response header If you create a cookie and send it to the browser, it is a session-level cookie by default : Stored in the browser's memory and deleted after the user exits the browser. If you want the browser to store this cookie on disk, you need to use maxAge and give a time in seconds. Setting the maximum duration to 0 instructs the browser to delete the cookie. Sending a cookie requires inserting the cookie into a Set-Cookie HTTP request header using the addCookie method of HttpServletResponse. Since this method does not modify any previously specified Set-Cookie headers, but instead creates new ones, we call this method addCookie instead of setCookie. Also keep in mind that response headers must be set before any document content is sent to the client.

6. Cookie reading 1. Call request.getCookie To obtain the cookie sent by the browser, you need to call the getCookies method of HttpServletRequest, which returns an array of Cookie objects, corresponding to the value input by the Cookie header in the HTTP request. 2. Loop through the array, calling the getName method of each cookie, until the cookie of interest is found. The cookie is related to your host (domain), not your servlet or JSP page. Thus, although your servlet may only be sending a single cookie, you may also get many unrelated cookies. For example: String cookieName = "userID"; Cookie cookies[] = request.getCookies(); if (cookies!=null){ for(int i=0;i<cookies.length;i++){ Cookie cookie = cookies[i ]; if (cookieName.equals(cookie.getName())){ doSomethingWith(cookie.getValue()); } } }

7. How to use cookies to detect first-time visitors A. Call HttpServletRequest.getCookies() to get the cookie array B. Retrieve in the loop whether the cookie with the specified name exists and whether the corresponding value is correct C. If so, exit the loop and set the distinguishing mark D . Determine whether the user is a first-time visitor and perform different operations according to the distinguishing identifier

8. Common mistakes in using cookies to detect first-time visitors A user cannot be considered a first-time visitor just because a particular data item does not exist in the cookie array. If the cookie array is null, the client may be a first-time visitor, or it may be the result of the user deleting or disabling cookies. However, if the array is non-null, it just shows that customers have been to your website or domain, not that they have visited your servlet. Other servlets, JSP pages, and non-Java Web applications can set cookies, and depending on the path, any cookie may be returned to the user's browser. The correct way is to judge whether the cookie array is empty and whether the specified Cookie object exists and the value is correct.

9. Notes on using the cookie attribute Attributes are part of the header sent from the server to the browser; but they are not part of the header returned by the browser to the server. So aside from the name and value, the cookie attributes only apply to cookies sent from the server to the client; server-side cookies from the browser do not have these attributes set. So don't expect this property to be used in cookies obtained via request.getCookies. This means that you can't achieve a constantly changing cookie value just by setting the maximum age of the cookie, issuing it, looking for the appropriate cookie in the subsequent input array, reading its value, modifying it and saving it back into the cookie .

10. How to use cookies to record the visit count of each user Object 4. Reset the maximum time limit 5. Output the new cookie

十一、session在不同环境下的不同含义   session,中文经常翻译为会话,其本来的含义是指有始有终的一系列动作/消息,比如打电话是从拿起电话拨号到挂断电话这中间的一系列过程可以称之为一个session。   然而当session一词与网络协议相关联时,它又往往隐含了“面向连接”和/或“保持状态”这样两个含义。   session在Web开发环境下的语义又有了新的扩展,它的含义是指一类用来在客户端与服务器端之间保持状态的解决方案。有时候Session也用来指这种解决方案的存储结构。

十二、session的机制   session机制是一种服务器端的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。   但程序需要为某个客户端的请求创建一个session的时候,服务器首先检查这个客户端的请求里是否包含了一个session标识-称为session id,如果已经包含一个session id则说明以前已经为此客户创建过session,服务器就按照session id把这个session检索出来使用(如果检索不到,可能会新建一个,这种情况可能出现在服务端已经删除了该用户对应的session对象,但用户人为地在请求的URL后面附加上一个JSESSION的参数)。   如果客户请求不包含session id,则为此客户创建一个session并且生成一个与此session相关联的session id,这个session id将在本次响应中返回给客户端保存。

十三、保存session id的几种方式 A.保存session id的方式可以采用cookie,这样在交互过程中浏览器可以自动的按照规则把这个标识发送给服务器。 B.由于cookie可以被人为的禁止,必须有其它的机制以便在cookie被禁止时仍然能够把session id传递回服务器,经常采用的一种技术叫做URL重写,就是把session id附加在URL路径的后面,附加的方式也有两种,一种是作为URL路径的附加信息,另一种是作为查询字符串附加在URL后面。网络在整个交互过程中始终保持状态,就必须在每个客户端可能请求的路径后面都包含这个session id。 C.另一种技术叫做表单隐藏字段。就是服务器会自动修改表单,添加一个隐藏字段,以便在表单提交时能够把session id传递回服务器。

十四、session什么时候被创建   一个常见的错误是以为session在有客户端访问时就被创建,然而事实是直到某server端程序(如Servlet)调用HttpServletRequest.getSession(true)这样的语句时才会被创建。

十五、session何时被删除 session在下列情况下被删除: A.程序调用HttpSession.invalidate() B.距离上一次收到客户端发送的session id时间间隔超过了session的最大有效时间 C.服务器进程被停止   再次注意关闭浏览器只会使存储在客户端浏览器内存中的session cookie失效,不会使服务器端的session对象失效。

十六、URL重写有什么缺点   对所有的URL使用URL重写,包括超链接,form的action,和重定向的URL。每个引用你的站点的URL,以及那些返回给用户的URL(即使通过间接手段,比如服务器重定向中的Location字段)都要添加额外的信息。   这意味着在你的站点上不能有任何静态的HTML页面(至少静态页面中不能有任何链接到站点动态页面的链接)。因此,每个页面都必须使用servlet或 JSP动态生成。即使所有的页面都动态生成,如果用户离开了会话并通过书签或链接再次回来,会话的信息都会丢失,因为存储下来的链接含有错误的标识信息-该URL后面的SESSION ID已经过期了。  

十七、使用隐藏的表单域有什么缺点 仅当每个页面都是有表单提交而动态生成时,才能使用这种方法。单击常规的<A HREF..>超文本链接并不产生表单提交,因此隐藏的表单域不能支持通常的会话跟踪,只能用于一系列特定的操作中,比如在线商店的结账过程。

十八、会话跟踪的基本步骤 1.访问与当前请求相关的会话对象 2.查找与会话相关的信息 3.存储会话信息 4.废弃会话数据

十九、getSession()/getSession(true)、getSession(false)的区别 getSession()/getSession(true):当session存在时返回该session,否则新建一个session并返回该对象 getSession(false):当session存在时返回该session,否则不会新建session,返回null

二十、如何将信息与会话关联起来   setAttribute会替换任何之前设定的值;如果想要在不提供任何代替的情况下移除某个值,则应使用removeAttribute。这个方法会触发所有实现了HttpSessionBindingListener接口的值的valueUnbound方法。

二十一、会话属性的类型有什么限制吗   通常会话属性的类型只要是Object就可以了。除了null或基本类型,如int,double,boolean。   如果要使用基本类型的值作为属性,必须将其转换为相应的封装类对象

二十二、如何废弃会话数据 A.只移除自己编写的servlet创建的数据: 调用removeAttribute(“key”)将指定键关联的值废弃 B.删除整个会话(在当前Web应用中): 调用invalidate,将整个会话废弃掉。这样做会丢失该用户的所有会话数据,而非仅仅由我们servlet或JSP页面创建的会话数据 C.将用户从系统中注销并删除所有属于他(或她)的会话 调用logOut,将客户从Web服务器中注销,同时废弃所有与该用户相关联的会话(每个Web应用至多一个)。这个操作有可能影响到服务器上多个不同的Web应用。

二十三、使用isNew来判断用户是否为新旧用户的错误做法   public boolean isNew()方法如果会话尚未和客户程序(浏览器)发生任何联系,则这个方法返回true,这一般是因为会话是新建的,不是由输入的客户请求所引起的。   但如果isNew返回false,只不过是说明他之前曾经访问该Web应用,并不代表他们曾访问过我们的servlet或JSP页面。   因为session是与用户相关的,在用户之前访问的每一个页面都有可能创建了会话。因此isNew为false只能说用户之前访问过该Web应用,session可以是当前页面创建,也可能是由用户之前访问过的页面创建的。   正确的做法是判断某个session中是否存在某个特定的key且其value是否正确

二十四、Cookie的过期和Session的超时有什么区别   会话的超时由服务器来维护,它不同于Cookie的失效日期。首先,会话一般基于驻留内存的cookie不是持续性的cookie,因而也就没有截至日期。即使截取到JSESSIONID cookie,并为它设定一个失效日期发送出去。浏览器会话和服务器会话也会截然不同。

二十五、session cookie和session对象的生命周期是一样的吗   当用户关闭了浏览器虽然session cookie已经消失,但session对象仍然保存在服务器端

二十六、是否只要关闭浏览器,session就消失了   程序一般都是在用户做log off的时候发个指令去删除session,然而浏览器从来不会主动在关闭之前通知服务器它将要被关闭,因此服务器根本不会有机会知道浏览器已经关闭。服务器会一直保留这个会话对象直到它处于非活动状态超过设定的间隔为止。   之所以会有这种错误的认识,是因为大部分session机制都使用会话cookie来保存session id,而关闭浏览器后这个session id就消失了,再次连接到服务器时也就无法找到原来的session。   如果服务器设置的cookie被保存到硬盘上,或者使用某种手段改写浏览器发出的HTTP请求报头,把原来的session id发送到服务器,则再次打开浏览器仍然能够找到原来的session。   恰恰是由于关闭浏览器不会导致session被删除,迫使服务器为session设置了一个失效时间,当距离客户上一次使用session的时间超过了这个失效时间时,服务器就可以认为客户端已经停止了活动,才会把session删除以节省存储空间。   由此我们可以得出如下结论:   关闭浏览器,只会是浏览器端内存里的session cookie消失,但不会使保存在服务器端的session对象消失,同样也不会使已经保存到硬盘上的持久化cookie消失。

二十七、打开两个浏览器窗口访问应用程序会使用同一个session还是不同的session   通常session cookie是不能跨窗口使用的,当你新开了一个浏览器窗口进入相同页面时,系统会赋予你一个新的session id,这样我们信息共享的目的就达不到了。   此时我们可以先把session id保存在persistent cookie中(通过设置session的最大有效时间),然后在新窗口中读出来,就可以得到上一个窗口的session id了,这样通过session cookie和persistent cookie的结合我们就可以实现了跨窗口的会话跟踪。

二十八、如何使用会话显示每个客户的访问次数   由于客户的访问次数是一个整型的变量,但session的属性类型中不能使用int,double,boolean等基本类型的变量,所以我们要用到这些基本类型的封装类型对象作为session对象中属性的值   但像Integer是一种不可修改(Immutable)的数据结构:构建后就不能更改。这意味着每个请求都必须创建新的Integer对象,之后使用setAttribute来代替之前存在的老的属性的值。例如: HttpSession session = request.getSession(); SomeImmutalbeClass value = (SomeImmutableClass)session.getAttribute(“SomeIdentifier”); if (value= =null){ value = new SomeImmutableClass(…); // 新创建一个不可更改对象 }else{ value = new SomeImmutableClass(calculatedFrom(value)); // 对value重新计算后创建新的对象 } session.setAttribute(“someIdentifier”,value); // 使用新创建的对象覆盖原来的老的对象

二十九、如何使用会话累计用户的数据   使用可变的数据结构,比如数组、List、Map或含有可写字段的应用程序专有的数据结构。通过这种方式,除非首次分配对象,否则不需要调用setAttribute。例如 HttpSession session = request.getSession(); SomeMutableClass value = (SomeMutableClass)session.getAttribute(“someIdentifier”); if(value = = null){ value = new SomeMutableClass(…); session.setAttribute(“someIdentifier”,value); }else{ value.updateInternalAttribute(…); // 如果已经存在该对象则更新其属性而不需重新设置属性 }

三十、不可更改对象和可更改对象在会话数据更新时的不同处理   不可更改对象因为一旦创建之后就不能更改,所以每次要修改会话中属性的值的时候,都需要调用 setAttribute(“someIdentifier”,newValue)来代替原有的属性的值,否则属性的值不会被更新可更改对象因为其自身一般提供了修改自身属性的方法,所以每次要修改会话中属性的值的时候,只要调用该可更改对象的相关修改自身属性的方法就可以了。这意味着我们就不需要调用 setAttribute方法了。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326558179&siteId=291194637