当前位置: 移动技术网 > IT编程>开发语言>Java > 深入Ajax代理的Java Servlet的实现详解

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

2019年07月22日  | 移动技术网IT编程  | 我要评论
代码如下所示:复制代码 代码如下: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;
 }
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网