【问题标题】:Access servlet declared HttpSession in jsp在jsp中访问servlet声明的HttpSession
【发布时间】:2014-04-04 08:07:39
【问题描述】:

如果登录 servlet 中的用户名、密码和位置正确,我将创建一个 HttpSession 并进入 jsp 页面。下面是servlet中的代码:

    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 中找不到符号变量 sessiona。请帮忙。自 2 天以来一直在谷歌上搜索它。

【问题讨论】:

    标签: jsp servlets httpsession


    【解决方案1】:

    这样做,首先在你的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");
    %>
    

    通过此您将从会话中获取用户和位置。希望这会对您有所帮助。

    【讨论】:

      【解决方案2】:

      您可以直接使用session变量(与请求关联的HttpSession对象),它在JSP中作为Implicit Objects可用。您可以使用会话对象而无需任何初始化或getSession()。

      session 对象在 JSP 中可用,如果您没有在 JSP 中包含以下行

      <%@ page session="false" %>  
      

      它将禁用包含它的 JSP 文件中的会话跟踪。如果此行包含在 JSP 中,则不能直接在 JSP 中使用session 对象。

      来自参考文档:

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

      【讨论】:

        【解决方案3】:

        您也可以尝试使用在每个 jsp 范围内预定义的会话变量直接获取值:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-22
          • 1970-01-01
          • 1970-01-01
          • 2021-08-23
          相关资源
          最近更新 更多