如何将请求从Filter转发到另一个URL并获得结果?
我正在使用Filter
和HttpClient.execute()
方法转发请求。这种方式是正确的吗?
以下是代码:
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
...
HttpRequestBase method = null;
URI uri = null;
if (isPost) {
method = new HttpPost();
} else {
method = new HttpGet();
}
uri = new URI(newUrl);
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
method.setHeader(header, request.getHeader(header));
}
method.setURI(uri);
HttpResponse downstreamResponse = httpClient.execute(method);
ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
downstreamResponse.getEntity().writeTo(baos);
OutputStream responseStream = response.getOutputStream();
responseStream.write(responseBytes);
答案 0 :(得分:0)
在你的
中doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
您收到了ServletResponse
因此您可以将其投放到HttpServletResponse
HttpServletResponse httpResponse = (HttpServletResponse) res;
httpResponse.sendRedirect("/login.jsp");