2013-04-11 123 views
0

有什么方法可以将请求URL更改为指向托管在其他Web服务器中的另一个页面?假设我有在Tomcat中托管的网页:更改请求URL以指向servlet过滤器中的不同Web服务器

<form action="http://localhost:8080/Test/dummy.jsp" method="Post"> 
    <input type="text" name="text"></input> 
    <input type="Submit" value="submit"/> 
</form> 

我拦截使用Servlet过滤器的要求:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,ServletException { 
    HttpServletRequest request = (HttpServletRequest) req; 
    chain.doFilter(req, res); 
    return; 
} 

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

回答

1

HttpServletResponse#sendRedirect()默认发送一个HTTP 302重定向,它实际上隐式地创建一个新的GET请求。

您需要改为HTTP 307重定向。

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

(我假设http://localhost URL仅仅是示范性的;这显然不会在生产工作)

注:浏览器会要求确认,然后再继续。

另一种方法是,为代理玩:

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

再一种选择是将PHP代码移植到JSP/Servlet代码。另一种选择是通过PHP模块(如Quercus)在Tomcat上直接运行PHP。

相关问题