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.

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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题