Jetty的ProxyServlet.Transparent类的用法示例

时间:2011-11-17 18:41:12

标签: proxy jetty transparent dynamic-proxy

我正在尝试使用jetty7来构建透明的代理设置。想法是将原始服务器隐藏在jetty服务器后面,以便传入的请求可以以透明的方式转发到源服务器。

我想知道我是否可以使用jetty的ProxyServlet.Transparent实现来实现。如果是的话,任何人都可以给我一些例子。

1 个答案:

答案 0 :(得分:7)

此示例基于Jetty-9。如果要使用Jetty 8实现此功能,请实现proxyHttpURI方法(请参阅Jetty 8 javadocs。)。这是一些示例代码。

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.servlets.ProxyServlet;

/**
 * When a request cannot be satisfied on the local machine, it asynchronously
 * proxied to the destination box. Define the rule 
 */
public class ContentBasedProxyServlet extends ProxyServlet {
    private int remotePort = 8080;

    public void setPort(int port) {
        this.remotePort = port;
    }

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        super.service(request, response);
    }

    /**
     *  Applicable to Jetty 9+ only. 
     */
    @Override
    protected URI rewriteURI(HttpServletRequest request) {
        String proxyTo = getProxyTo(request);
        if (proxyTo == null)
            return null;
        String path = request.getRequestURI();
        String query = request.getQueryString();
        if (query != null)
            path += "?" + query;
        return URI.create(proxyTo + "/" + path).normalize();
    }

    private String getProxyTo(HttpServletRequest request) {
    /*
    *   Implement this method: All the magic happens here. Use this method to figure out your destination machine address. You can maintain
    *   a static list of addresses, and depending on the URI or request content you can route your request transparently.
    */
    }
}

此外,您可以实现一个过滤器,用于确定请求是否需要在本地计算机或目标计算机上终止。如果请求是针对远程计算机的,请将请求转发给此servlet。

// Declare this method call in the filter.
request.getServletContext()
    .getNamedDispatcher("ContentBasedProxyServlet")
    .forward(request, response);