この例は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.
*/
}
}
さらに、ローカルコンピュータまたは宛先コンピュータで要求を終了する必要があるかどうかを判断するフィルタを実装できます。要求がリモートマシン用である場合は、このサーブレットに要求を転送します。
// Declare this method call in the filter.
request.getServletContext()
.getNamedDispatcher("ContentBasedProxyServlet")
.forward(request, response);
私はこのソリューションをjetty 9で試しましたが、動作しません。これは、service()メソッドで何らかの理由でNullPointerExceptionを送出しています。 – FearUs
推奨事項を作るには、スタックトレースや実際のコードなどの情報が必要になります。ほとんどの場合、NPEはgetProxyTo()メソッドまたはrewriteURI()メソッドのいずれかからバブルアップします。 – systemboot
@ user766453サンプルは素晴らしいです。しかし、私は直面している - javax.servlet.ServletException:java.lang.IllegalStateException:プロキシのサーバーエグゼキュータがありません。あなたはなにか考えはありますか?私はここで私の質問をしました - http://stackoverflow.com/questions/27624873/proxyservlet-stop-working-after-migration-from-jetty-8-to-jetty-9 –