简体   繁体   中英

How to send parameters from a servlet

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM