dongyuan9892 2013-04-11 09:11
浏览 73
已采纳

将请求URL更改为指向servlet过滤器中的不同Web服务器

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?

  • 写回答

1条回答 默认 最新

  • dongxiangqian1855 2013-04-11 12:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?