Iam not able to pass a value from servlet to jsp using setAttribute and getAttribute.

My test code :

Test1.jsp
=======

<%@ page language="java" contentType="text/html" %>
<html>
<head><title>Login Example</title></head> 
<body>
Enter Your Text
<hr><p>
<form name = login action="../servlet/TestServlet1" method=POST>
Your Text : <input type=text name=yourText><br>
<input type=submit value=LogIn>
</form>
</body>
</html>

TestServlet1.java
============

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet1 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

// initalize some variables
HttpSession session = request.getSession(true);
String userText = request.getParameter("yourText");
session.setAttribute("myText", userText);
RequestDispatcher rd = request.getRequestDispatcher("/../TEST/Test2.jsp");
rd.forward(request, response);
}
}
}

Test2.jsp
=======

<%@ page language="java" contentType="text/html" %>
<% String up = (String)session.getAttribute("myText"); %>

<html>
<head><title>Login Example</title></head> 
<body>
<% if (up == null) 
{ %>
its null again
<% } else { 
%>
<%= up %> is my text!<br>
<% } %>
</body>
</html>

All the time iam getting null from getAttribute.

<% String up = (String)session.getAttribute("myText"); %>

When i printed the sessionId in the servlet and both jsp (Test1,Test2), it showed thw same session id
the session id is same but the attributes which i set is not there...

code for printing session id
===================

String id = session.getId();
System.out.println(id);

can anyone help me in this ?
Thanks in advance

Since you are using a forward, there is no need to use session variables. The HttpServletRequest is preserved when forwarding.

instead of this
<% String up = (String)session.getAttribute("myText"); %>


try this
<% String up = session.getAttribute("myText").toString(); %>


The session attribute is of object datatype.so we have to convert it to string .

> try this <% String up = session.getAttribute("myText").toString(); %> .

...which would anyways throw a NullPointerException in this case.

> The session attribute is of object datatype.so we have to convert it to string .

What? The ` session ' variable is of the type ` HttpSession '.

This article has been dead for over six months. Start a new discussion instead.