tags:

views:

277

answers:

2

Hello, I am trying to use a RequestDispatcher to send parameters from a servlet.

Here is my servlet code:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

 String station = request.getParameter("station");
 String insDate = request.getParameter("insDate");

 //test line
 String test = "/response2.jsp?myStation=5";

 RequestDispatcher rd;
 if (station.isEmpty()) {
     rd = getServletContext().getRequestDispatcher("/response1.jsp");

 } else {
     rd = getServletContext().getRequestDispatcher(test);
 }

 rd.forward(request, response);

}

Here is my jsp, with the code to read the value - however it shows null.

    <h1>response 2</h1>
    <p>
        <%=request.getAttribute("myStation")  %>
    </p>

Thanks for any suggestions. Greener

A: 

Use getParameter(). An attribute is set and read internally within the application.

erickson
+3  A: 

In your servlet use request.setAttribute in the following manner

request.setAttribute("myStation", value);

where value happens to be the object you want to read later.

and extract it later in a different servlet/jsp using request.getAttribute as

String value = (String)request.getAttribute("myStation")

or

<%= request.getAttribute("myStation")>

Do note that the scope of usage of get/setAttribute is limited in nature - attributes are reset between requests. If you intend to store values for longer, you should use the session or application context, or better a database.

Attributes are different from parameters, in that the client never sets attributes. Attributes are more or less used by developers to transfer state from one servlet/JSP to another. So you should use getParameter (there is no setParameter) to extract data from a request, set attributes if needed using setAttribute, forward the request internally using RequestDispatcher and extract the attributes using getAttribute.

Vineet Reynolds
Thank for the extensive comments. I really appreciate. The passed values have a page scope, so I think the method you showed me would be sufficient.
Greener
You're welcome :)
Vineet Reynolds