如何从Filter重定向到另一台主机?

时间:2014-03-20 08:15:59

标签: java servlets redirect httpresponse servlet-filters

如何将请求从Filter转发到另一个URL并获得结果?

我正在使用FilterHttpClient.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);

1 个答案:

答案 0 :(得分:0)

在你的

doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) 

您收到了ServletResponse

因此您可以将其投放到HttpServletResponse

HttpServletResponse httpResponse = (HttpServletResponse) res;
httpResponse.sendRedirect("/login.jsp");