Is there any way to change the request URL to point to another page hosted in different web server? Suppose I have a page hosted in Tomcat:
<form action="http://localhost:8080/Test/dummy.jsp" method="Post">
<input type="text" name="text"></input>
<input type="Submit" value="submit"/>
</form>
And I intercept the request using a servlet filter:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,ServletException {
HttpServletRequest request = (HttpServletRequest) req;
chain.doFilter(req, res);
return;
}
What I want is to change the request URL to point to a PHP page hosted in another web server http://localhost/display.php
. I know that I can use response.sendRedirect
, but it won't work in my case because it discards all POST data. Is there any way to change the request URL so that chain.doFilter(req, res);
will forward me to that PHP page?
The HttpServletResponse#sendRedirect()
sends by default a HTTP 302 redirect which indeed implicitly creates a new GET request.
You need a HTTP 307 redirect instead.
response.setStatus(307);
response.setHeader("Location", "http://localhost/display.php");
(I assume that the http://localhost
URL is just exemplary; this obviously won't work in production)
Note: browsers will ask for confirmation before continuing.
An alternative would be to play for proxy:
URLConnection connection = new URL("http://localhost/display.php").openConnection();
connection.setDoOutput(true); // POST
// Copy headers if necessary.
InputStream input1 = request.getInputStream();
OutputStream output1 = connection.getOutputStream();
// Copy request body from input1 to output1.
InputStream input2 = connection.getInputStream();
OutputStream output2 = response.getOutputStream();
// Copy response body from input2 to output2.
Note: you'd better use a servlet for this instead of a filter.
Again another alternative would be to just port PHP code to JSP/Servlet code. Again another alternative would be to run PHP straight on Tomcat via a PHP module such as Quercus.