为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

session的用法(The use of session)

2017-09-21 17页 doc 54KB 39阅读

用户头像

is_266065

暂无简介

举报
session的用法(The use of session)session的用法(The use of session) session的用法(The use of session) 5.2 Session mechanism In addition to using Cookie, Web applications often use Session to record client status. Session is a mechanism used by the server to record the state of the client, which is simp...
session的用法(The use of session)
session的用法(The use of session) session的用法(The use of session) 5.2 Session mechanism In addition to using Cookie, Web applications often use Session to record client status. Session is a mechanism used by the server to record the state of the client, which is simpler to use than Cookie, and also increases the storage pressure of the server. 5.2.1 what is Session? Session is another mechanism for recording customer status; unlike, Cookie is stored in the client browser, and Session is stored on the server. When the client browser accesses the server, the server records client information in some form on the server. This is Session. When the client browser accesses again, it is only necessary to look for the status of the customer from the Session. If the Cookie mechanism determines the identity of a customer by checking the "pass" on the customer, then the Session mechanism is to verify the identity of the customer by checking the "customer list" on the server. Session is equivalent to a client file set up by the program on the server. When the customer visits, he only needs to check the customer file form. 5.2.2 implements user login The class corresponding to Session is the javax.servlet.http.HttpSession class. Each visitor corresponds to a Session object, where all of the customer's status information is stored in the Session object. The Session object is created when the client first requests the server. Session is also a property of key-value, which reads and writes customer status information by means of getAttribute (String, key) and setAttribute (String, key, Object, value) methods. Servlet gets the customer's Session through the request.getSession () method, for example: HttpSession = request.getSession (session); / / get the Session object Session.setAttribute ("loginTime"), new (Date); / / set attribute in Session Out.println (login time:: + (Date) session.getAttribute ('loginTime')); / / get the Session property Request can also use getSession (Boolean create) to get Session. The difference is that if the customer's Session does not exist, the request.getSession () method returns null, while getSession (true) creates the Session first and returns the Session. Servlet must use request to programmatically obtain HttpSession objects, while JSP has built-in Session hidden objects that can be used directly. If you use the page statement <%@ session= "false" Session% >, the hidden object is not available. The following example uses Session to record customer account information. The source code is as follows: Code 5.9 session.jsp <%@ page language= "Java" pageEncoding= "UTF-8"% > < Response.setCharacterEncoding ("UTF-8"); / / set request encoding Person[] persons = {/ / basic data, save three personal information New Person ("Liu Jinghua", "password1", 34, dateFormat.parse ("1982-01-01")), "New Person" ("Hello Kitty"", "hellokitty", 23, dateformat.parse (1984) - (25)). new person ("garfield", "garfield _ pass", 23, dateformat.parse (1994) - 09 - 12 ") }; message = "string"; / / 要显示的消息 if (request.getmethod ().equals ("post") {/ / 如果是post登 录 for (2): () {/ / 遍历基础数据, 验证账号、密码 / / / / / / / / 如果 用户名正确 且 密码正确 if (person.getname () (request.getparameter.equalsignorecase ("username") .equals & person.getpassword () (request.getparameter ("password"))) { / / / / / / / / 登录成功, 设置将用户的信息以及登录时间保存到 session session.setattribute ("person", 保存登录的person)); / / session.setattribute (logintime, new date (). / / / / / / / / / / / / / / 保存登录的时间 response.sendredirect (request.getcontextpath () + / welcome.jsp "); return; } } message = "用户名密码不匹配, 登录失败; / / 登录失败." } % > > > > > > < html > / / / / / / / / / / / / / /. html代码为一个form表单, 代码 略, 请看随书光盘 < html > 登录界面验证用户登录信息, 如果登录正确, 就把用户信息以及登 录时间保存进session, 然后转到欢迎页面 welcome.jsp.welcome.jsp中从session中获取信息, 并将用户资料 显示出来.welcome.jsp代码如下. welcome.jsp 代码 5.10. (% @ page language = "java" pageencoding = "utf-8"% "jsp: directive.page import =" com.helloweenvsfei.sessionweb.bean.person "/ > "jsp: directive.page import =" java.text.simpledateformat "/ > "jsp: directive.page import =" java.text.dateformat "/ > "jsp: directive.page import =" java.util.date "/ > <%. dateformat dateformat = new simpledateformat (yyyy mm dd). / / / / / / / / / / / / / / 日期格式化器 % > > > > > > (%) a person (person) session.getattribute ("person"). / / / / / / / / / / / / / / 获取登录的person logintime = (date) date (logintime session.getattribute "); / / / / / / / / / / / / / / 获取登录时间 % > > > > > > / / / / / / / / / / / / / /. 部分html代码略 < table > < tr > < td > 您的姓名. < / td > < td > <% = person.getname (% > < / td > < / tr > < tr > < td > 登录时间. < / td > < td > < %,%,,,TD >登录时间 < > < > < >您的年龄TR TD:< / TD > < td > < % =人。getage() %,,,TD > < > < > < >您的生日TR TD:< / TD > < > < %= TD日期格式。格式(的人。getbirthday())%,,,TD > < > <表> 5.8所示程序运行效果如图。 5.8届图使用用户信息 程序中使用了一个java bean类人,源代码请参看随书光盘。注意程序中会话中直接保存了人类对象与日期类对象,使用起来要比饼干方便。 当多个客户端执行程序时,服务器会保存多个客户端的会话。获取会话的时候也不需要声明获取谁的会话。会话机制决定了当前客户只会获取到自己的会话,而不会获取到别人的各客户的也彼此独立互不可见会话,会话。 %提示:会话cookie方便的使用比,但是过多的会话存储在服务器内存中,会对服务器造成压力。 5.2.3会议的生命周期 会议保存在服务器端。为了获得更高的存取速度,服务器一般把会话 放在内存里。每个用户都会有一个独立的会话。如果会话内容过于复杂,当大量客户访问服务器时可能会导致内存溢出因此里的信息应该尽量精简,会话。 会议在用户第一次访问服务器的时候自动创建。需要注意只有访问JSP Servlet等程序时才会创建、会话,只访问HTML、图像等静态资源并不会创建会话。如果尚未生成会话,也可以使用请求。getsession(真的)强制生成会话。 会议生成后,只要用户继续访问,服务器就会更新会话的最后访问时间,并维护该会话。用户每访问服务器一次,无论是否读写会话,服务器都认为该用户的会话”活跃(主动)”了一次。 5.2.4会议的有效期 由于会有越来越多的用户访问服务器,因此会话也会越来越多。为防止内存溢出,服务器会把长时间内没有活跃的会话从内存删除。这个时间就是的超时时间如果超过了超时时间没访问过服务器,会话就自动失效了会话。 会议的超时时间为maxinactiveinterval属性,可以通过对应的getmaxinactiveinterval()获取,通过setmaxinactiveinterval(长时间)修改。 会议的超时时间也可以在网站。XML中修改。另外,通过调用会话的invalidate()方法可以使会话失效。 5.2.5会议的常用方法 会议中包括各种方法,使用起来要比cookie会话的常用方法如表5.2所示方便得多。 5.2表HttpSession的常用方法 方法名描述 无效的setAttribute(字符串属性,对象的值)设置会话属性。价 值参数可以为任何java对象。通常为java bean。价值信息不宜过 大 字符串(字符串属性中)返回会话属性 枚举getattributenames()返回会话中存在的属性名 无效removeattribute(字符串属性)移除会话属性 返回会话ID字符串getid()的该ID由服务器自动创建, Not repeat Long getCreationTime () returns the creation date of the Session. The return type is long and is often converted to the Date type, for example: Date createTime = new Date (session.get CreationTime ()) Long getLastAccessedTime () returns the last active time of Session. The return type is long Int getMaxInactiveInterval () returns the timeout time of Session. Units per second. More than that time without access, the server considers the Session invalid Void setMaxInactiveInterval (int second) sets the timeout time of the Session. Units per second Void putValue (String, attribute, Object, value) is not recommended. Has been replaced by setAttribute (String, attribute, Object, Value) Object getValue (String attribute) is not recommended. Has been replaced by getAttribute (String, attr) Boolean isNew () Returns whether the Session is new Void invalidate () causes the Session to fail The default timeout time for Session in Tomcat is 20 minutes. Modify timeout by setMaxInactiveInterval (int, seconds). You can modify web.xml to change the default timeout time for Session. For example, change to 60 minutes: 60 - unit: Min -- > % note: the units of the parameter are minutes, while the setMaxInactiveInterval (int, s) units are seconds. 5.2.6 Session's browser requirements Although Session is kept on the server and transparent to the client, its normal operation still requires the support of client browsers. This is because Session needs to use Cookie as the identification mark. The HTTP protocol is stateless, Session not on the HTTP connection to determine whether the same client, so the server to the client browser sends a JSESSIONID Cookie, its value is the Session ID (HttpSession.getId) (the return value). Session identifies whether the same user is based on the Cookie. The Cookie is automatically generated for the server, and its maxAge attribute is typically - 1, indicating that only the current browser is valid and that the browser window is not shared and that the browser is disabled if it is closed. Therefore, when two browser windows of the same machine access the server, two different Session are generated. However, a new window opened by a link, script, etc in the browser window (that is, not double the open window of the desktop browser icon). These child windows share the Cookie of the parent window, so they share a Session. % note: the new browser window generates new Session, except the child window. The child window shares the Session of the parent window. For example, right-click on the link, and then in the pop-up shortcut menu select "open in the new window", then the child window can access the Session of the parent window. What if the client browser disables the Cookie function or does not support Cookie? For example, the vast majority of mobile browsers do not support Cookie. Java Web provides another solution: URL address rewriting. 5.2.7 URL address rewriting URL address rewriting is a solution that does not support Cookie on the client side. The principle of URL address rewriting is to rewrite the ID information of the user Session to the URL address. The server is able to parse the rewritten URL to get the ID of Session. Thus, even if the client does not support Cookie, you can also use Session to record user status. The HttpServletResponse class provides encodeURL (String, URL) to implement URL address rewriting, for example: >" Homepage This method automatically determines whether the client supports Cookie. If the client supports Cookie, the URL will be left intact. If the client does not support Cookie, the user's Session's ID is rewritten to URL. The output after rewriting may be like this: Homepage" That is, after the name of the file, string is added to the front of the URL parameter; jsessionid=XXX". Where XXX is the ID of Session. As you can see, the added jsessionid string does not affect the file name of the request, nor does it affect the address field parameter submitted. When the user clicks this link, the Session's ID is submitted to the server via URL, and the server gets the Session ID by parsing the URL address. If it is a page redirection (Redirection), the URL address rewrite can be written this way: < If ("Administrator",.Equals (userName)) { Response.sendRedirect (response.encodeRedirectURL ("administrator.jsp")); Return; } % > The effect is the same as that of response.encodeURL (String URL): if the client supports Cookie, the original URL address is generated, and if the Cookie is not supported, the rewritten address with the jsessionid string is returned. For WAP programs, since most mobile browsers do not support Cookie, the WAP program uses URL address rewriting to track user sessions. For example, UF group mobile business street, etc.. % notice: TOMCAT determines whether the client browser supports Cookie based on whether the request contains Cookie. Although the client may support Cookie, but because the first request will not carry any Cookie (since no Cookie can carry it), the address of the URL address will still have jsessionid after rewriting. When second accesses, the server has written Cookie in the browser, so the address of the URL address will not be overwritten with jsessionid. 5.2.8 Session is prohibited from using Cookie Since most of the client browsers on the WAP do not support Cookie, it's better to simply ban Session from using Cookie and unify the use of URL addresses. The Java Web specification supports disabling Cookie by configuration. Here's an example of how you can use Cookie without configuration. Open the META-INF folder under the WebRoot directory of the project sessionWeb (at the same level as the WEB-INF folder, if not created) and open context.xml (if not created). Edit the content as follows: Code 5.11 /META-INF/context.xml < XML, version='1.0', encoding='UTF-8' > > Or modify the global conf/context.xml of Tomcat, modify the contents as follows: Code 5.12 context.xml Contents of this ... After deployment, TOMCAT will not automatically become famous JSESSIONID Cookie, Session will not use Cookie as the identification mark, but only the rewritten URL address as the identification mark. % note: this configuration simply prohibits Session from using Cookie as an identification flag, and does not prevent other Cookie from reading and writing. That is, the server does not automatically maintain the Cookie named JSESSIONID, but the program can still read and write other Cookie. Comparison of 5.3 Session and Cookie Both Cookie and Session can do session tracking, but the implementation is not the same principle. Generally, the two can meet the demand, But sometimes you can't use Cookie, and sometimes you can't use Session. The following illustrates the characteristics of the two and the applicable occasions. 5.3.1 compares access modes ASCII strings can only be saved in Cookie, and if you want to access Unicode characters or binary data, you need to encode UTF-8, GBK, or BASE64. Nor can Cookie directly access Java objects. To store slightly complex information, using Cookie is difficult. In Session, you can access any type of data, including, not limited to, String, Integer, List, Map, and so on. Session can also directly save Java, Bean, and any Java class, objects, and so on. It's very convenient to use. You can think of Session as a Java container class. 5.3.2 compares privacy and security Cookie is stored in the client browser and is visible to the client, and some programs on the client side may snoop, copy, or even modify the content in the Cookie. While Session is stored on the server, it is transparent to the client, and there is no danger of sensitive information leakage. If you choose Cookie, the better way is to have sensitive information, such as account number, password, and so on, so as not to write to Cookie. It is better to encrypt Cookie information, submit it to the server and decrypt it, like Google and Baidu, and make sure that the information in Cookie is read by yourself. And if you choose Session, it's much easier, anyway, it's on the server, and any privacy in Session can be. 5.3.3 from the validity of the comparison People who have used Google know that if Google is logged in, the login message for Google is valid for a long time. Users don't have to log in every time they visit, and Google logs the user's login information for a long time. To achieve this effect, the use of Cookie would be a better choice. Just set the maxAge attribute of Cookie to a very large number or Integer.MAX_VALUE. The maxAge attribute of Cookie supports this effect. This effect can also be achieved theoretically using Session. Just call the method setMaxInactiveInterval (Integer. MAX_VALUE), is that all right?. But because the Session depends on the name JSESSIONID Cookie, Cookie JSESSIONID and maxAge - 1 as the default, as long as the Session closes the browser will fail, so Session can not achieve permanent effective information. Rewriting using URL addresses is also not possible. Moreover, if the timeout time for setting Session is too long, the more Session accumulated by the server, the more likely it is to cause memory overflow. 5.3.4 compares the load on the server Session is saved on the server side, and each user generates a Session. If concurrent access to a large number of users, will produce a very large number of Session, consume a lot of memory. As a result, sites with high concurrent access like Google, Baidu, and Sina are unlikely to use Session to track customer conversations. The Cookie is saved on the client side and does not occupy server resources. Cookie is a good choice if there are so many concurrent users. For Google, Baidu, and Sina, Cookie is probably the only option. 5.3.5 compares browser support Cookie requires client browser support. If the client disables Cookie, or does not support Cookie, then the session trace fails. Conventional Cookie is useless for applications on WAP. If the client browser does not support Cookie, you need to overwrite it with Session and URL addresses. Note that all Session procedures used URL to use response.encodeURL (String URL) or response.encodeRedirectURL (String URL) URL address rewriting, otherwise cause the Session session tracking failure. For WAP applications, Session+URL address rewriting may be the only option. If the client supports Cookie, Cookie can be set to the browser window and effectively in a sub window (set maxAge - 1), also can be effective in all browser windows (the maxAge is set to an integer greater than 0). But Session only in the browser window and sub window effectively. If the two browser window is irrelevant to each other, they will use two different Session. 5.3.6 from cross domain comparison Cookie supports cross domain access, for example, the domain property is set to ".Helloweenvsfei.com" to ".Helloweenvsfei.com" for all the domain name suffix can access the Cookie. Cross domain Cookie is now widely used in the network, such as Google, Baidu, Sina etc.. While Session does not support cross domain access. Session is only valid in his domain name. % note: only use Cookie or use only Session may not achieve the ideal effect. You should try to use Cookie and Session. Cookie and Session collocation in the actual use of the project will achieve gorgeous effect. 5.4 summary of this chapter Cookie is in the early stage of the session tracking technology, it will save the information to the client browser. Browser to access the site will carry the Cookie information to identify the purpose. Session is built on the basis of the Cookie session tracking technology, it will be the information stored in the server, the Java object storage responsible to Session, so the use of more convenient. Session relies on the name JSESSIONID Cookie. If the client browser does not support Cookie, or disable Cookie, still can use Session by using the URL address rewrite.
/
本文档为【session的用法(The use of session)】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索