【问题标题】:Change request URL to point to different web server in servlet filter更改请求 URL 以指向 servlet 过滤器中的不同 Web 服务器
【发布时间】:2013-04-03 10:01:21
【问题描述】:

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

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

【问题讨论】:

    标签: php jsp redirect servlet-filters


    【解决方案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 代码。另一种选择是通过 Quercus 等 PHP 模块直接在 Tomcat 上运行 PHP。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-31
      • 2016-03-13
      • 2017-08-20
      • 2014-09-13
      • 2023-03-20
      • 2011-01-09
      相关资源
      最近更新 更多