📜  JSP 会话——隐式对象

📅  最后修改于: 2022-05-13 01:55:36.721000             🧑  作者: Mango

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); %>  


示例 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
 
 

例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); %>  

输出:它们按顺序如下: