user595234
user595234

Reputation: 6259

how to include Servlet request parameters to a new JSP page?

In the Java Servlet, how to include original paramters after response ?

Servlet
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cmd = request.getParameter("cmd");
        System.out.println("service , cmd="+cmd);
        request.setAttribute("name", "John"+System.currentTimeMillis());
        RequestDispatcher rd = request.getRequestDispatcher("process.jsp");
        rd.include(request, response);
    }

JSP
main ${name}<br>
cmd ${cmd}
  1. If I want to include all paramters, like "cmd", to a new jsp page, how to do it ?
  2. based on No.1, if I want to add NEW attributes, like "name" to a new jsp page, how to do it ?
  3. In the above codes, use include or forward, the results are same. why ?

Thanks

Upvotes: 1

Views: 3608

Answers (3)

Anantha Sharma
Anantha Sharma

Reputation: 10098

you can access all the request params using the request.getParameterMap() another question which can help you method, this returns a map of all params (key-value pair) which you can iterate and set the attribute.

request.setAttribute("name", "John"+System.currentTimeMillis());

What you've done here does add a new attribute called name (provided another entry doesn't exist with the key as name).

The result of include and forward are the same as

  • you are not adding any specific content to the response
  • when you forward a request, you are forwarding the control to handle the response to another component (in your case process.jsp) when you include a jsp in your request, you are executing the included component and have the option of adding something extra to the stream (which you aren't doing). thats why both the actions show you the same result.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

It's the same request, you don't need to do anything at all.

A forward means you can't have committed any response (no output to client). Include doesn't allow any response status code or header changes.

See the docs for forward/include.

Upvotes: 1

BalusC
BalusC

Reputation: 1108722

If I want to include all paramters, like "cmd", to a new jsp page, how to do it ?

All request parameters are in EL available by the ${param} map.

${param.cmd}

You don't need to prepare anything in the servlet.


based on No.1, if I want to add NEW attributes, like "name" to a new jsp page, how to do it ?

You already did it by request.setAttribute("name", name) and ${name}.


In the above codes, use include or forward, the results are same. why ?

Not exactly. If you use include(), the delegatee would not be able to control the response headers. You should be using forward() in this case. See also the javadoc. You should use include() only if you want to append something before and after instead of fully delegating the request/response.

See also:

Upvotes: 3

Related Questions