JSP 会话——隐式对象
在 JSP 中,会话是最常用的HttpSession类型的隐式对象。它主要用于接近用户的所有数据,直到用户会话处于活动状态。
session隐式对象中使用的方法如下:
方法一: isNew():这个方法用于检查会话是否是新的。它返回布尔值(真或假)。它主要用于跟踪客户端是否启用了 cookie。如果未启用 cookie,则session.isNew()方法应始终返回 true。
方法 2: getId():在创建会话时,servlet 容器为会话分配一个独特的字符串标识符。这个独特的字符串标识符由getId方法返回。
方法三: getAttributeNames():通过getAttributeNames方法返回session中存储的所有对象。从根本上说,此方法会导致枚举对象。
方法四: getCreationTime():通过getCreationTime方法返回会话创建时间(会话变为活动状态或会话开始的时间)。
方法 5: getAttribute(String name):使用getAttribute方法,从会话中检索由 setAttribute() 方法存储的对象。例如,我们需要使用 setAttribute() 方法将“userid”存储在 session 中,如果需要在每个 jsp 页面上访问 userid,直到 session 处于活动状态,并且在需要时可以使用 getAttribute() 方法访问它。
方法6: setAttribute(String, object): setAttribute方法用于通过为对象分配唯一的字符串来将对象存储在会话中。稍后,通过使用相同的字符串,可以从会话访问此对象,直到会话处于活动状态。在 JSP 中,在处理会话时 setAttribute() 和 getAttribute() 是两个最常用的方法。
方法 7: getMaxInactiveInterval():getMaxInactiveInterval 返回会话的最大停用时间间隔(以秒为单位)。
方法八: getLastAccessedTime:getLastAccessedTime方法主要用于注意会话的最后访问时间。
方法9: removeAttribute(String name):使用removeAttribute(String name)方法,可以从会话中删除存储在会话中的对象。
方法 10: invalidate(): invalidate()方法结束会话并断开会话与所有存储对象的连接。
执行:
下面给出的“ index.html”页面将显示一个文本框和一个 go 按钮。点击 go 按钮后,控制被转移到welcome.jsp 页面。最后附加所有输出。
示例 1: index.html
HTML
Insert title here
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Insert title here
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
Display the value
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Insert title here
Display the session value on this page
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
The name which is entered by user in the index page is displayed on the welcome.jsp page and it saves the same variable in the session object so that it can be retrieved on any page till the session becomes inactive.
示例 2(A): welcome.jsp
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Insert title here
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
Display the value
In second.jsp page, the value of variable is retrieved from the session and displayed.
例2(B) second.jsp
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Insert title here
Display the session value on this page
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
输出:它们按顺序如下: