Send Post request in java with response.sendRedirect method

早过忘川 提交于 2019-11-30 14:00:50
Alex

According to RFC2616 with HTTP/1.1 you can send 307 response code, which will make user-agent to repeat it's POST request to provided host. In your case just do

response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", url);

response is your HttpServletResponse object.

Hope this helps.

When a browser receives an HTTP redirect code it will always perform a GET or HEAD to the given url by standard. This is why data must be sent by query strings. If you want to simulate a redirect by POST, you can send to your client a form with the information you want and, on the page load event, you automatically submit the form using Javascript (commonly used to comunicate between different servers, used by SAML protocol for example). Here's an example:

<form name="myRedirectForm" action="https://processthis.com/process" method="post">
    <input name="name" type="hidden" value="xyz" />
    <input name="phone" type="hidden" value="9898989898" />
    <noscript>
        <input type="submit" value="Click here to continue" />
    </noscript>
</form>
<script type="text/javascript">

    $(document).ready(function() {
        document.myRedirectForm.submit();
    });

</script>

Side note: If you already have the information in your server why are you sending a redirect instead of doing the given action? Maybe you want to implement a POST/REDIRECT/GET pattern?

I do not think this is possible. Why do not you use RequestDispatcher. This will work for you. Just set the parameters in request

request.setAttribute("message", "Hello test");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);

OR - The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue.

OR - another option, set the parameters in your session in servlet, if you have session. Then get it from session after you redirect to the required page.

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