Java – redirect to another port, keeping all remaining ports
On the server (embedded jetty), I need to redirect to another port, leaving everything else unchanged, for example, redirection
@H_ 404_ 8@
@H_ 404_ 8@
http://com.example.myserver:1234/whatever?with=params#and-hash?and=whokNowswhat
To @ h_ 404_ 8@
@H_ 404_ 8@
http://com.example.myserver:5678/whatever?with=params#and-hash?and=whokNowswhat
It seems that I have to write the result URL from something I don't know: @ h_ 404_ 8@
>Server name used by browser > remainder of URL @ h_ 404_ 8@
Solution
Out of the box rewrite handler
@H_ 404_ 8@
http://wiki.eclipse.org/Jetty/Feature/Rewrite_Handler @H_ 404_ 8@
I took a quick look at jetty's rewriting handler out of the box From the content I can collect from documents / examples, it seems that they are actually rewritten only in the path part of the URL (that is, all content after the port, not what we want) (if I am wrong, please correct me!)@ H_ 404_ 8@
Write request handler @ h_ 404_ 8@
A basic example to get you started. If you only want to use embedded jetty, you can write a request handler to redirect all requests to a given port@ H_ 404_ 8@
The way it works is that portredirector uses the handle method to handle HTTP requests It builds the original request URL, changes the port to the target "to" port, and redirects the client to the new URL@ H_ 404_ 8@
In the following example, the server listens on port 1234 and redirects all requests to port 8080@ H_ 404_ 8@
@H_ 404_ 8@
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: @ h_ 404_ 8@
> Get full URL and query string in Servlet for both HTTP and HTTPS requests@H_404_8 @