Java http反向代理,带有响应HTML URL重写

时间:2018-05-14 10:39:17

标签: servlets url-rewriting servlet-filters

我希望我的Java Web应用程序能够使用由其他Web服务器提供的无缝代理内容。

http://myapp.com/proxy/* -> http://other_app_to_proxy.com:9090/

我的应用程序将处理所有与auth相关的事务,并在同一域下的子路径上提供其他应用程序。

我找到了如何进行反向代理:HTTP-Proxy-Servlet

现在的问题是其他应用程序有绝对网址,例如/css/style.css,当我的应用程序中的网页打开时,无法访问此网址,因为我的设置应该是/proxy/css/style.css

我发现我需要某种URL重写过滤器来改变发送到客户端的出站响应。我尝试研究Tuckey UrlRewrite,但看起来它的目的不同 - 它有很多工具可以更改入站网址并将请求重定向到其他位置。

有人可以指点我一些解决方案吗?

4 个答案:

答案 0 :(得分:0)

我找到了几个允许在过滤器中完全响应正文重写的类。

几个基类:

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public abstract class AbstractResponseAlteringFilter implements Filter {

    public void init(FilterConfig fConfig) throws ServletException {
    }

    protected static class ByteArrayServletStream extends ServletOutputStream {
        ByteArrayOutputStream baos;

        ByteArrayServletStream(ByteArrayOutputStream baos) {
            this.baos = baos;
        }

        public void write(int param) throws IOException {
            baos.write(param);
        }
    }

    protected static class ByteArrayPrintWriter {

        private ByteArrayOutputStream baos = new ByteArrayOutputStream();

        private PrintWriter pw = new PrintWriter(baos);

        private ServletOutputStream sos = new ByteArrayServletStream(baos);

        public PrintWriter getWriter() {
            return pw;
        }

        public ServletOutputStream getStream() {
            return sos;
        }

        byte[] toByteArray() {
            return baos.toByteArray();
        }
    }

    protected static class CharResponseWrapper extends HttpServletResponseWrapper {
        private ByteArrayPrintWriter output;
        private boolean usingWriter;

        public CharResponseWrapper(HttpServletResponse response) {
            super(response);
            usingWriter = false;
            output = new ByteArrayPrintWriter();
        }

        public byte[] getByteArray() {
            return output.toByteArray();
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            // will error out, if in use
            if (usingWriter) {
                super.getOutputStream();
            }
            usingWriter = true;
            return output.getStream();
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            // will error out, if in use
            if (usingWriter) {
                super.getWriter();
            }
            usingWriter = true;
            return output.getWriter();
        }

        public String toString() {
            return output.toString();
        }
    }

    public void destroy() {
    }
}



import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

public abstract class AbstractResponseBodyAlteringFilter extends AbstractResponseAlteringFilter {

    private final static Logger logger = LoggerFactory.getLogger(AbstractResponseBodyAlteringFilter.class);


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        CharResponseWrapper wrappedResponse = new CharResponseWrapper(httpResponse);
        chain.doFilter(request, wrappedResponse);

        logger.info("wrappedResponse.getContentType() = {}", wrappedResponse.getContentType());

        byte[] responseBytes = wrappedResponse.getByteArray();
        if (StringUtils.containsAny(wrappedResponse.getContentType(), "text/", "javascript")) {
            responseBytes = modifyResponseBody(new String(responseBytes, "UTF-8")).getBytes("UTF-8");
        }
        OutputStream out = httpResponse.getOutputStream();

        logger.info("wrappedResponse.getStatus() = {}", wrappedResponse.getStatus());

        httpResponse.setStatus(wrappedResponse.getStatus());
        httpResponse.setContentType(wrappedResponse.getContentType());

        httpResponse.setContentLength(responseBytes.length);
        out.write(responseBytes);
        out.flush();
        httpResponse.flushBuffer();
    }

    protected abstract String modifyResponseBody(String body);

}

这里是最终用户类:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

public class ProxyResponseBodyRewriteFilter extends AbstractResponseBodyAlteringFilter {

    @Value("${proxy.filter.prefix:/proxy/}")
    String prefix;

    private final static Logger logger = LoggerFactory.getLogger(ProxyResponseBodyRewriteFilter.class);

    protected String modifyResponseBody(String body) {
        body = body.replaceAll("href\\s*=\\s*\"\\s*/", "href=\"" + prefix);
        body = body.replaceAll("src\\s*=\\s*\"\\s*/", "src=\"" + prefix);
        body = body.replace("</head>", "<base href=\"/proxy/\"></head>");
        return body;
    }

}

答案 1 :(得分:0)

我正面临类似的问题,不仅要使用引用的HttpProxyServlet,而且还需要更改响应中嵌入的URL。作为子类ProxyServlet的一部分,我做了以下工作,并且它可以工作(尽管代码仍然偏向我的用例,并且不完全通用),但是我很好奇您是否发现过一些更简单/已经编写的东西,@下雪了?

public class CustomProxyServlet extends ProxyServlet {

    @Override
    protected void copyResponseEntity(
            HttpResponse proxyResponse, HttpServletResponse servletResponse,
            HttpRequest proxyRequest, HttpServletRequest servletRequest
        ) throws IOException {

        HttpEntity entity = proxyResponse.getEntity();
        if (entity != null) {
            OutputStream servletOutputStream = servletResponse.getOutputStream();
            if (isRewritable(proxyResponse)) {
                RewriteOutputStream rewriter = null;
                try {
                    rewriter = new RewriteOutputStream(servletOutputStream);
                    entity.writeTo(rewriter);
                }
                finally { rewriter.flush(); }
            }
            else {
                // parent's default behavior
                entity.writeTo(servletOutputStream);
            }
        }
    }

    private boolean isRewritable(HttpResponse httpResponse) {
        boolean rewriteable = false;
        Header[] contentTypeHeaders = httpResponse.getHeaders("Content-Type");
        for (Header header : contentTypeHeaders) {
            // May need to accept other types
            if (header.getValue().contains("html")) rewriteable = true;
        }
        return rewriteable;
    }
}

RewriteOutputStream在哪里

public class RewriteOutputStream extends FilterOutputStream {
    // Provided implementation based on BufferedOutputStream adding
    // config-based string replacement before writing to output.
}

答案 2 :(得分:0)

无可否认,这是一种变通方法,而不是实际的解决方案,但此信息可能对控制代理应用程序的人有用。我们能够按原样使用 Smiley 的代理 Servlet,并且通过使用与代理 servlet 使代理页面可用的结构相匹配的结构来部署代理应用程序,从而避免了必须进行 URL 重写。

http://myapp.com/proxy/* -> http://other_app_to_proxy.com:9090/proxy/*

答案 3 :(得分:-2)

尝试在您的反向代理服务器的配置文件中将位置/代理更改为/ proxy /(尾部斜杠)。

如果您使用nginx作为反向代理服务器,请参阅链接。

https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/