jsp实现 AJAX 跨域代理

jsp实现 AJAX 跨域代理2008-04-17 17:39

http://hi.baidu.com/afeiecho/blog/item/6afe39ec878946382697918f.html

proxy.jsp:

<%@ page import="java.net.*,java.util.*,java.lang.*,java.io.*"%><%@ page contentType="text/xml;charset=gb2312"%><% 
String url = null;
StringBuffer params = new StringBuffer();
Enumeration enu = request.getParameterNames();
int total = 0;
while (enu.hasMoreElements()) {
String paramName=(String)enu.nextElement();
if(paramName.equals("url")){
   url=request.getParameter(paramName);
}else{
   if(total==0){
    params.append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
   } else {
    params.append("&").append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
   }
   ++total;
}
}
url = url + "?" + params.toString();
//out.println(url);
if(url != null){
// 使用GET方式向目的服务器发送请求
URL connect = new URL(url.toString());
URLConnection connection = connect.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = reader.readLine()) != null){
   out.println(line);
}
reader.close();
}
%>

AJAX中不能直接访问http://www.otherpersondomain.com/a.jsp?param1=&param2=

所以通过访问proxy.jsp代理访问:

proxy.jsp?url=http://www.otherpersondomain.com/a.jsp&param1=&param2=
 

上一篇:一起谈.NET技术,在ASP.NET MVC3 中利用JSONP跨域登录WEB系统


下一篇:深入浅出JSONP--解决ajax跨域问题