0

I am trying to forward a request using "RequestDispatcher". I have JSP pageContext object. I tried to forward my request to my servlet "MyServlet" using the following code. I set some attributes in my request and forwarded it. But i am not able to access those variables in my servlet class.

My code :

pageContext.getRequest().setAttribute("AValue","A");
pageContext.getRequest().setAttribute("BValue", "B");

ServletContext context= pageContext.getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/MyServlet");
rd.forward(pageContext.getRequest(),pageContext.getResponse());

Help me !! Thanks in advance.

Kalidha
  • 21
  • 4
  • can you showw the code what is the code in MyServlet to get attribute from request. The code written above along with question is this inside a jsp? If it is in jsp why don't you simply right request.setAttribute("AValue","A") instead of pageContext.getRequest().setAttribute("AValue","A"); because request is an implicit object in jsp. – Ravi Kumar Dec 23 '13 at 09:05
  • Thanks for ur reply.I am using this code in one of my server codes. From my custom tag library class I got this pageContext object and passed it to my server class.In my server class based on some condition I forward the request to various servlets. Code to get the attribute values : String aValue = (String) request.getAttribute("AValue"); – Kalidha Dec 23 '13 at 10:33

1 Answers1

0

When dynamically including or forwarding to a servlet from a JSP page, you can use a jsp:param tag to pass data to the servlet.

A jsp:param tag is used within a jsp:include or jsp:forward tag.

<jsp:include page="/servlet/MyServlet" flush="true" >
  <jsp:param name="AValue" value="A" />
  <jsp:param name="BValue" value="B" />
</jsp:include>

Here is source docs

The use of scriptlets <% %> in JSP is indeed highly discouraged since decade.
See How to avoid Java Code in JSP-Files?

Community
  • 1
  • 1
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
  • Thanks for the reply.I am not forwarding my request directly from my JSP. I need to forward my request through RequestDispatcher. Is there any other way? – Kalidha Dec 23 '13 at 10:38
  • I tried the following code, pageContext.getRequest().setAttribute("check","checkValue"); RequestDispatcher rd = pageContext.getRequest().getRequestDispatcher("/MyServlet"); rd.forward(pageContext.getRequest(),pageContext.getResponse()); and in my servlet class, String v = (String) request.getAttribute("check"); System.out.println("Check value : " +v); Still it is printing null value...Any idea? – Kalidha Dec 23 '13 at 12:09