更改请求URL以指向servlet过滤器中的其他Web服务器 [英] Change request URL to point to different web server in servlet filter

查看:80
本文介绍了更改请求URL以指向servlet过滤器中的其他Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以更改请求URL以指向不同Web服务器中托管的另一个页面?假设我在Tomcat中托管了一个页面:

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>

然后我使用servlet过滤器拦截了请求:

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;
}

我想要的是更改请求URL以指向另一个Web服务器http://localhost/display.php中托管的PHP页面.我知道我可以使用response.sendRedirect,但是在我的情况下它将不起作用,因为它会丢弃所有POST数据.有什么方法可以更改请求URL,以便chain.doFilter(req, res);会将我转发到该PHP页面?

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?

推荐答案

默认情况下,HttpServletResponse#sendRedirect()发送HTTP 302重定向,该重定向确实隐式创建了一个新的GET请求.

The HttpServletResponse#sendRedirect() sends by default a HTTP 302 redirect which indeed implicitly creates a new GET request.

您需要HTTP 307重定向.

You need a HTTP 307 redirect instead.

response.setStatus(307);
response.setHeader("Location", "http://localhost/display.php");

(我假设http://localhost URL仅是示例性的;显然,这在生产中将不起作用)

(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.

另一种选择是代理:

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.

注意:为此,您最好使用 servlet 而不是过滤器.

Note: you'd better use a servlet for this instead of a filter.

另一种替代方法是将PHP代码移植到JSP/Servlet代码.同样,另一种选择是通过Quercus之类的PHP模块直接在Tomcat上运行PHP.

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.

这篇关于更改请求URL以指向servlet过滤器中的其他Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆