Este ejemplo se basa en Jetty-9. Si desea implementar esto con Jetty 8, implemente el método proxyHttpURI (consulte Jetty 8 javadocs). Aquí hay un código de muestra.
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.
*/
}
}
Adicionalmente, se puede implementar un filtro que determina si la petición tiene que terminar en la máquina local o en la máquina de destino. Si la solicitud es para la máquina remota, envíe la solicitud a este servlet.
// Declare this method call in the filter.
request.getServletContext()
.getNamedDispatcher("ContentBasedProxyServlet")
.forward(request, response);
Probé esta solución con el muelle 9, y no funciona. Me está dando una NullPointerException por algún motivo en el método service(). – FearUs
Necesitaré más información, como rastros de pila o código real, para hacer cualquier recomendación. Lo más parecido es que el NPE está burbujeando desde el método getProxyTo() o el método rewriteURI(). – systemboot
@ user766453 la muestra es increíble. Sin embargo, estoy frente a - javax.servlet.ServletException: java.lang.IllegalStateException: No servidor ejecutor para proxy. ¿Tienes alguna idea? He hecho mi pregunta aquí - http://stackoverflow.com/questions/27624873/proxyservlet-stop-working-after-migration-from-jetty-8-to-jetty-9 –