2014-03-03 79 views
1

如果用戶名,密碼和位置在登錄servlet中正確,我正在創建一個HttpSession並進入jsp頁面。下面是servlet中的代碼:訪問servlet在jsp中聲明HttpSession

HttpSession sessionsa = request.getSession(true); 
    sessionsa.setAttribute("user",userName); //userName is a String variable 
    sessionsa.setAttribute("location",location); //location in value place is a String variable 

現在在jsp頁面上,我無法訪問屬性。 jsp上的代碼:

sessionsa = request.getSession(); 
    String user = (String) sessionsa.getAttribute("user"); 
    String location = (String) sessionsa.getAttribute("location"); 

它聲明在類SimplifiedJSPServlet中找不到符號變量sessionsa。請幫忙。自2天以來一直在使用Google。

回答

3

這樣做,首先使您的jsp中的會話創建爲false。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1" session="false"%> 

然後獲取會話,

<% 
HttpSession sessionsa = request.getSession(false); 
String user = (String) sessionsa.getAttribute("user"); 
String location = (String) sessionsa.getAttribute("location"); 
%> 

通過這一點,你會得到從session.Hope用戶和位置,這將幫助你。

1

您可以直接使用session變量(與請求關聯的HttpSession對象),它可以在JSP中作爲Implicit Objects使用。您可以使用會話對象,而無需任何初始化或getSession()。

session對象在JSP可如果你還沒有包括以下線在JSP

​​

它將在JSP文件中禁用會話跟蹤其所included.If此行包含在JSP你不能可以直接在JSP中使用session對象。

從Rererence DOC:

JSP Implicit Objects are the Java objects that the JSP Container makes available 
to developers in each page and developer can call them directly without being 
explicitly declared. 

在你的情況,你可以使用下面的代碼。

String user = (String) session.getAttribute("user"); 
String location = (String) session.getAttribute("location"); 
0

您也可以嘗試使用它在每個JSP的範圍預先定義會話變量直接讀取值:

(String)session.getAttribute("name");