9

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

1
  • RequestDispatcher is not used to read parameters. Hence I've edited your post. Sep 10, 2009 at 19:32

3 Answers 3

17

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.

1
  • 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
    Sep 10, 2009 at 20:05
3

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

2

In your code, String test = "/response2.jsp?myStation=5";

You are adding myStation=5 as query string.As the query string parameters are stored as request parameters in Request Object.

Therefore you can use ,

It works fine.Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.