Rahul Kumar
Rahul Kumar

Reputation: 399

Session attribute not reflected in JSP

So I have jsp one that loads some request params as a session which I access in my second jsp .

My jsp 1 code is :

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

My jsp 2 code is :

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

Now I can see the <p> in the first jsp populated properly with the data but the paragraph in my second jsp just blank

when I change session.setAttribute( "allEmail",email); to something like session.setAttribute( "allEmail","hello world); I can see the correct value reflected in both paragraphs .

What am I doing wrong ?

the servlet that populates jsp1 has the following request dispatcher

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

I think the issue is both the jsp's are initialised at the same time so the session in the second jsp has no value .

Upvotes: 1

Views: 2316

Answers (2)

Prasad
Prasad

Reputation: 3795

What you want to pass here is a String into session scope. 1) You don't require a jsp useBean for this. You can directly set in session scope with scriptlet you currently have.

To use jsp useBean tag, the component class should be of type JavaBean. You are using String class which is immutable. And so you cannot set any property for String to be used in useBean. Unfortunately scriptlet error was not captured/not thrown (don't know) when you are assigning with

    String email = Emails;

Why it was working when you are setting?

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

This is as good as setting:

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

If you want to pass some String property along with other properties if required, define like:

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

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

and then set property as:

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

Upvotes: 0

Sireesh Yarlagadda
Sireesh Yarlagadda

Reputation: 13736

As per the above scenario. Since request will hold the session object for sure.

You can try this :-

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

Upvotes: 1

Related Questions