Vge Shi
Vge Shi

Reputation: 213

Passing string variable from servlet to jsp

I am opening in browser link mapped to my servlet, and expect to display the passed value. But what i see is "null"

Servlet:

public class TestServlet extends HttpServlet {    
    public TestServlet() {
        super();       
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {           
            request.setAttribute("var", "a"); 
            request.getRequestDispatcher("index.jsp").forward(request, response);    
    }


}

jsp:

<% 
String  s1  = (String) session.getAttribute("var");        
%>
<%= s1 %>

Upvotes: 1

Views: 15749

Answers (3)

Gautam vasudeva
Gautam vasudeva

Reputation: 1

SERVLET part:

String str = request.getParameter("str1");
request.setAttribute("str1", "hello, welcome!! how are you??");
getServletContext().getRequestDispatcher("/Demo.jsp").forward(request,response);

JSP part (is to be included in any tag paragraph or textbox etc)

${str}

Upvotes: 0

Omiye Jay Jay
Omiye Jay Jay

Reputation: 449

Instead of accessing the attribute via a session scope in the jsp page you could simply change your

String  s1  = (String) session.getAttribute("var");  

to

    String s1 = request.getAttribute("var");

or if you still want to access it via a session scope you could set the variable in a session scope in your servlet for example:

Http session = request.getSession();
     session.setAttribute("var","a");

then you could just access it the same way you are doing in the JSP page or you could simply do what David said :

 request.getSession().setAttribute("var", "a");

either way would work.

Upvotes: 0

David Levesque
David Levesque

Reputation: 22441

The problem is that you are setting the attribute in the request scope but are reading it from the session scope. Try replacing this line:

request.setAttribute("var", "a");

by this one:

request.getSession().setAttribute("var", "a");

This way you will refer to session scope in both places. Alternatively, you can use the request scope in both places by using request.getAttribute() in your JSP.

Upvotes: 1

Related Questions