这里主要解决ajax跨全域的问题,而且主要使用后台代理的方式实现。
前台ajax处理:
Ext.Ajax.request({
url : '×××.action' //后台代理action
callback: function(options,success,response){
}
});
后台代理action
/**
* 代理前台进行跨域访问
* @throws Exception
*/
public void domainProxy() throws Exception{
// 变量初始化
HttpServletRequest request = ServletActionContext.getRequest();
String url = "www.baidu.com" ; //http请求地址,即需要跨域进行访问的地址,例如“www.baidu.com”
String str = executeGet(url); //发送请求,跨域访问
JsonUtil.OutJsonString(str) ; //以json形式,返回ajax请求数据
}
后台http发送请求函数(参考http://ipfire.iteye.com/blog/978063)
/**
* 使用HttpClient获取HttpGet请求
* @throws Exception
*/
@SuppressWarnings("finally")
public String executeGet(String url) throws Exception {
BufferedReader in = null;
String content = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8")); //解决中文乱码问题
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
content = sb.toString();
} finally {
if (in != null) {
try {
in.close();// 最后要关闭BufferedReader
} catch (Exception e) {
e.printStackTrace();
}
}
return content;
}
}
此处http请求用到了jar包,注意引入commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar。下载地址:http://www.eu.apache.org/dist/httpcomponents/httpclient/binary/