1

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 %>
Vge Shi
  • 203
  • 2
  • 3
  • 10

3 Answers3

1

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.

David Levesque
  • 22,181
  • 8
  • 67
  • 82
  • I would do the opposite and change the jsp to call request.getAttribute(). The OP doesn't state he needs session scope and this will prevent the value being held in memory for longer than its needed - the request rather than the user's session. – Will Sep 24 '13 at 21:57
  • @David Levesque dont suggest to use scripplets,use jstl instead – SpringLearner Sep 25 '13 at 04:19
0

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.

Omiye Jay Jay
  • 409
  • 5
  • 10
  • 19
0

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}

JohnnyQ
  • 1,591
  • 1
  • 16
  • 25