用AjaxProxyServlet 跨域ajax请求

老庄的代码里用了DataInputStream,这个类的readLine()不被推荐使用,所以换成了 InputStreamReader
添加了代码来处理Ajax请求中的参数。
java 代码
 
  1. /* 
  2.  * Created on 2007-1-16 
  3.  */  
  4. import javax.servlet.http.HttpServlet;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;

    import java.net.URL;

    import java.util.Enumeration;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class AjaxProxyServlet extends HttpServlet {
        protected void service(HttpServletRequest req,
                               HttpServletResponse resp) throws ServletException,
                                                                IOException {
            resp.setContentType("text/html");
            PrintWriter pw = resp.getWriter();
            Enumeration paramNames = req.getParameterNames();
            StringBuffer bfParams = new StringBuffer();
            bfParams.append(req.getParameter("url")).append("?1=1");
            while(paramNames.hasMoreElements()) {
                String param = (String)paramNames.nextElement();
                if("url".equals(param)){continue;}
                bfParams.append("&").append(param).append("=").append(req.getParameter(param));
            }
            
            URL url = new URL(bfParams.toString());
            BufferedReader bf =
                new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = bf.readLine()) != null) {
                pw.println(line);
            }
            bf.close();
        }
    }

你可能感兴趣的:(java,html,Ajax,.net,servlet)