欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

深入Ajax代理的Java Servlet的实现详解

程序员文章站 2023-12-14 15:07:28
代码如下所示:复制代码 代码如下:import java.io.ioexception;import java.io.inputstream;import java.net...
代码如下所示:
复制代码 代码如下:

import java.io.ioexception;
import java.io.inputstream;
import java.net.url;
import javax.servlet.servletconfig;
import javax.servlet.servletexception;
import javax.servlet.servletoutputstream;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
/**
 * take any request and proxy it to the given redirect_base.
 * for example, if this servlet lives at
 *
 * http://foo.com/forward
 *
 * and is inititialized with the redirect_base
 *
 * http://bar.com/some/path
 *
 * then a get request like
 *
 * http://foo.com/forward?quux=mumbley
 *
 * will return the results of a get from
 *
 * http://bar.com/some/path?quux=mumbley
 *
 * this is not robust and generalized; it's simple and quick.
 *
 * @author jdf
 *
 */
public class proxyservlet extends httpservlet
{
 private final static string copyright = com.ibm.dogear.copyright.short;
 public static final string redirect_base = "com.ibm.bl.servlet.redirectservlet.redirect_base";
 private string redirectbase;

 
 @override
 public void init(servletconfig config) throws servletexception
 {
  super.init(config);
  redirectbase = getrequiredparam(redirect_base);
 }
 @override
 protected void doget(httpservletrequest req, httpservletresponse resp) throws ioexception
 {
  string querystring = req.getquerystring();
  url url = new url(redirectbase + (querystring != null ? "?" + querystring : ""));
  copyinputstreamtooutputstream(url.openstream(), resp.getoutputstream());
 }
 private void copyinputstreamtooutputstream(inputstream in, servletoutputstream out)
   throws ioexception
 {
  try
  {
   try
   {
    byte[] buffer = new byte[1024];
    int n;
    while ((n = in.read(buffer)) != -1)
     out.write(buffer, 0, n);
   }
   finally
   {
    out.close();
   }
  }
  finally
  {
   in.close();
  }
 }
 protected string getrequiredparam(string param) throws servletexception
 {
  string result = getservletconfig().getinitparameter(param);
  if (result == null) {
   throw new servletexception(getclass() + " requires " + param + " param");
  }
  return result;
 }
}

上一篇:

下一篇: