Jetty反向代理


jetty 9.3.7中ProxyServlet类中取消了rewriteURI方法,以rewriteTarget方法取而代之。

rewriteTarget方法中返回的是反向代理的uri

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.proxy.AsyncProxyServlet;


public class MyProxyServlet extends AsyncProxyServlet{
	
	 /**
	 * 
	 */
	private static final long serialVersionUID = 4416222361054886895L;
	@Override
	 protected String rewriteTarget(HttpServletRequest request){
		 String uri = "http://www.sina.com.cn";
		 return uri;
	 
	 }
	
	


}

以代码中内嵌jetty的方式启动

import org.eclipse.jetty.proxy.AsyncProxyServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class Test {
	public static void main(String[] args) throws Exception {
		Server server = new Server(8080);
		ServletHandler handler = new ServletHandler();
		server.setHandler(handler);
		AsyncProxyServlet servlet = new MyProxyServlet();
		ServletHolder proxyServletHolder = new ServletHolder(servlet);
		proxyServletHolder.setAsyncSupported(true);
		proxyServletHolder.setInitParameter("maxThreads", "100");
		handler.addServletWithMapping(proxyServletHolder, "/*");
		server.start();
		server.join();

	}
}


如果需要对响应的报文做一些处理,可以重写newWriteListener方法

@Override

protected StreamWriter newWriteListener(HttpServletRequest request, Response proxyResponse)

  {

    return new MyStreamWriter(request, proxyResponse);

  }


protected class MyStreamWriter extends StreamWriter {


protected MyStreamWriter(HttpServletRequest arg0, Response arg1) {

super(arg0, arg1);

System.out.println("bbb");

System.out.println(arg1.toString());

}



}




你可能感兴趣的:(java)