远程服务器的RequestDispatcher? [英] RequestDispatcher for remote server?

查看:23
本文介绍了远程服务器的RequestDispatcher?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 HttpServlet,将所有传入请求按原样转发到另一个在不同域上运行的 serlvet.

I am trying to create a HttpServlet that forwards all incoming requests as is, to another serlvet running on a different domain.

如何实现?RequestDispatcher 的 forward() 只在同一台服务器上运行.

How can this be accomplished? The RequestDispatcher's forward() only operates on the same server.

我不能引入任何依赖项.

I can't introduce any dependencies.

推荐答案

当它不在同一个 ServletContext 或同一个/集群网络服务器中运行时你不能,其中 webapps 被配置为共享ServletContext(在Tomcat的情况下,检查crossContext选项).

You can't when it doesn't run in the same ServletContext or same/clustered webserver wherein the webapps are configured to share the ServletContext (in case of Tomcat, check crossContext option).

必须通过HttpServletResponse.sendRedirect().如果您实际关心的是在新 URL 上重用查询参数,只需重新发送它们.

You have to send a redirect by HttpServletResponse.sendRedirect(). If your actual concern is reusing the query parameters on the new URL, just resend them along.

response.sendRedirect(newURL + "?" + request.getQueryString());

或者当它是一个 POST 时,发送一个 HTTP 307 重定向,客户端将在新 URL 上重新应用相同的 POST 查询参数.

Or when it's a POST, send a HTTP 307 redirect, the client will reapply the same POST query parameters on the new URL.

response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", newURL);

<小时>

更新 根据评论,这显然不是一个选项,因为您想隐藏 URL.在这种情况下,您必须让 servlet 为代理服务.您可以使用 HTTP 客户端执行此操作,例如Java SE 提供了 java.net.URLConnection(这里的迷你教程)或更方便的Apache Commons HttpClient.


Update as per the comments, that's apparently not an option as well since you want to hide the URL. In that case, you have to let the servlet play for proxy. You can do this with a HTTP client, e.g. the Java SE provided java.net.URLConnection (mini tutorial here) or the more convenienced Apache Commons HttpClient.

如果是 GET,就这样做:

If it's GET, just do:

InputStream input = new URL(newURL + "?" + request.getQueryString()).openStream();
OutputStream output = response.getOutputStream();
// Copy.

或者如果是 POST:

Or if it's POST:

URLConnection connection = new URL(newURL).openConnection();
connection.setDoOutput(true);
// Set and/or copy request headers here based on current request?

InputStream input1 = request.getInputStream();
OutputStream output1 = connection.getOutputStream();
// Copy.

InputStream input2 = connection.getInputStream();
OutputStream output2 = response.getOutputStream();
// Copy.

请注意,您可能需要捕获/替换/更新 HTML 响应中的相关链接(如果有).Jsoup 在这方面可能会非常有帮助.

Note that you possibly need to capture/replace/update the relative links in the HTML response, if any. Jsoup may be extremely helpful in this.

这篇关于远程服务器的RequestDispatcher?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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