Does a RequestDispatcher forward maintain the original request's HTTP method?

浪子不回头ぞ 提交于 2020-01-12 06:52:08

问题


I want to intercept a request using the RequestDispatcher, and then I want to forward the request along to another servlet -- something like this:

RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/some.ThirdPartyServlet" + "?" + "param_name=" + "somevalue");
dispatcher.forward(request, response);

If the incoming request were a POST, will the request dispatcher take my new parameters, and include them in the message body, or does this forward now become a GET?


回答1:


It retains the original request, without changing it.

So, it will remain POST if it was POST.




回答2:


I think your concern is rather the availability of the passed-in request parameters (not attributes as others mentions). In this case it doesn't matter whether you use a forward or a redirect. But if you use a forward to another Servlet, then the appropriate method associated with the initial request as obtained by HttpServletRequest#getMethod() will be invoked. If it is POST, then doPost() will be invoked. You can still access the additional parameters in the query string the usual way by HttpServletRequest.getParameter().

So basically the following in servlet1:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    request.getRequestDispatcher("servlet2?foo=bar").forward(request, response);
}

can basically be handled by servlet2 as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String foo = request.getParameter("foo"); // Returns "bar".
}



回答3:


If you use forward, then control stays within the servlet container, the request attributes are retained, and the request remains a POST. It's when you use redirect that it causes a response to be sent to the browser causing it to make a GET request, which is where it loses the request attributes for the original request because the GET is an entirely new request.



来源:https://stackoverflow.com/questions/1940306/does-a-requestdispatcher-forward-maintain-the-original-requests-http-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!