Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send parameters from a servlet

Tags:

java

jsp

servlets

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

like image 789
Greener Avatar asked Sep 10 '09 18:09

Greener


2 Answers

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.

like image 117
Vineet Reynolds Avatar answered Nov 10 '22 00:11

Vineet Reynolds


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

like image 30
erickson Avatar answered Nov 09 '22 22:11

erickson