Out-Of-The-Box Rewrite Handlers
http://wiki.eclipse.org/Jetty/Feature/Rewrite_Handler
I had a quick look at the rewrite handlers provided by Jetty out of the box. From what I can gather from the documentation/examples, they all appear to do the actual rewriting on only the path part of the URL (i.e. everything after the ports, not quite what we want) (please correct me if I'm wrong!).
Writing a Request Handler
A rudimentary example to get you started, if you want to only use jetty embedded, you could write a request handler that would redirect all requests to the given port.
The way it works is the PortRedirector handles HTTP requests using the handle method. It builds the original request URL, changes the port to the target "to" port, and redirects the client to the new URL.
In the following example, the server listens to port 1234, and redirects all requests to port 8080.
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Redirector {
public static void main(String[] args) throws Exception {
Server server = new Server(1234);
server.setHandler(new PortRedirector(8080));
server.start();
server.dumpStdErr();
server.join();
}
static class PortRedirector extends AbstractHandler {
int to;
PortRedirector(int to) {
this.to = to;
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String uri = request.getScheme() + "://" +
request.getServerName() +
":" + to +
request.getRequestURI() +
(request.getQueryString() != null ? "?" + request.getQueryString() : "");
response.sendRedirect(uri);
}
}
}
References: