繁体   English   中英

会话属性未反映在JSP中

[英]Session attribute not reflected in JSP

所以我有一个jsp,它将一些请求参数作为会话加载到第二个jsp中。

我的jsp 1代码是:

<jsp:useBean id="Emails" scope="request" class="java.lang.String" />
<%

String email = Emails;
session.setAttribute( "allEmail",email);
%>

<p style="display:block" ><%= session.getAttribute( "allEmail" )%></p>

我的jsp 2代码是:

<p style="display:block" ><%= session.getAttribute( "allEmail" )%></p>

现在,我可以看到<p>一个jsp中的<p>正确地填充了数据,但是第二个jsp中的段落只是空白

当我更改session.setAttribute( "allEmail",email); 到诸如session.setAttribute( "allEmail","hello world);我可以看到两个段落中反映的正确值。

我究竟做错了什么 ?

填充jsp1的servlet具有以下请求分配器

RequestDispatcher dispatch = request.getRequestDispatcher("jsp1");

我认为问题在于两个jsp都在同一时间初始化,因此第二个jsp中的会话没有任何价值。

您要在此处传递的是进入会话范围的字符串。 1)您不需要使用jsp useBean。 您可以使用当前拥有的脚本直接在会话范围内进行设置。

要使用jsp useBean标记,组件类应为JavaBean类型。 您正在使用不可变的String类。 因此,您无法为要在useBean中使用的String设置任何属性。 不幸的是,当您分配时,scriptlet错误未捕获/未抛出(不知道)

    String email = Emails;

为什么设置时它可以正常工作?

    session.setAttribute( "allEmail","hello world"); 

这和设置一样好:

    <%
        String email = "hello world";
        session.setAttribute( "allEmail",email);
    %>

如果需要传递一些String属性以及其他属性,请定义如下:

    public class YourBean implements java.io.Serializable
    {
       private String propertyName = null;

       public String getPropertyName(){
          return propertyName;
       }
       public void setPropertyName(String propertyName){
          this.propertyName = propertyName;
       }
    }

然后将属性设置为:

    <jsp:useBean id="yourBean" class="package.YourBean" scope="bean scope">
       <jsp:setProperty name="yourBean" property="propertyName"  value="value"/>
       ...........
    </jsp:useBean>

按照上述方案。 因为请求肯定会保留会话对象。

您可以尝试:-

<p style="display:block" >
    <%(String)request.getSession().getAttribute("allEmails"); %>
</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM