How to send parameters from a servlet

I am trying to use 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 code to read the value - however, it shows null.

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

Thanks for any suggestions. Greener

+8
java jsp servlets
source share
3 answers

In your servlet, use request.setAttribute as follows

 request.setAttribute("myStation", value); 

where the value is the object you want to read later.

and extract it later to another servlet / jsp using request.getAttribute as

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

or

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

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

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

+15
source share

Use getParameter () . The attribute is set and read inside the application.

+3
source share

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

You add myStation = 5 as the query string. Because query string parameters are stored as query parameters in the query object.

Therefore you can use

It works great. Thanks.

+2
source share

All Articles