3

I had tried to pass string from servlet to jsp .But it never forwarded to jsp .The following are the files

servlet file:

String login = "asd";
request.setAttribute("myname",login);
request.getRequestDispatcher("GetCategory.jsp").forward(request, response); 

jsp file:

<% String name = (String)request.getAttribute("myname");
System.out.println(name);%>
Pravin
  • 645
  • 3
  • 7
  • 21

3 Answers3

3

I am a bit rusty in that topic but i think i used the forwarding this way:

String nextJSP = "/searchResults.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);

So getting the RequestDispatcher from the ServletContext rather than from the request, but im not sure if there is any difference behind the scenes of both calls.

Edit: Where do you set that attribute? (Is it in one of the two Methods doGet/doPost?

JBA
  • 2,769
  • 5
  • 24
  • 40
  • I tried , but still have the same problem in .. line 2 RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); – Pravin Nov 04 '13 at 10:51
  • Have you tried the answer of ByteCode? (I am going to delte my answer if its not helpful within the next couple of hours) – JBA Nov 04 '13 at 10:53
  • i tried . but still facing the same problem – Pravin Nov 04 '13 at 11:00
  • 1
    Can you try to add the following very simple example to your project and see if it works? http://www.java-tips.org/java-ee-tips/javaserver-pages/how-to-forward-requests-from-servlet-t.html – JBA Nov 04 '13 at 11:06
  • i set attribute in doGet – Pravin Nov 04 '13 at 11:09
  • O.k. so that is not the problem, try to add the above simple example which should work. I unfortunately dont have time to try it myself right now :( – JBA Nov 04 '13 at 11:13
  • example works well .. thank you ...now i am trying to pass arraylist from jsp to servlet which contains object ...guide me to do that – Pravin Nov 04 '13 at 11:23
  • I am trying like this... – Pravin Nov 04 '13 at 11:29
  • http://stackoverflow.com/questions/19766963/pass-arraylist-from-servlet-to-jsp – Pravin Nov 04 '13 at 11:40
  • Once you can pass a String-Object to your JSP you can pass anything else to your JSP as well :) Glad i could help you. – JBA Nov 04 '13 at 12:29
0

Use out.println(). out is implicit object in jsp.

your code would be.

<% 
   String name = (String)request.getAttribute("myname");
   out.println(name);
%>
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

Did you perhaps place the jsp file inside the WEB-INF folder or somewhere inside it? if so then you should change it to request.getRequestDispatcher("/WEB-INF/GetCategory.jsp").forward(request, response);

Nit
  • 1