jQuery與Servlet配合實現跨域請求:
方法:1.ajax post到servlet
2.servlet遠程訪問遠程url,並返回數據給頁面。
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
boolean requestType = false;//標記遠程請求類型,默認為GET方式
PrintWriter out = resp.getWriter();
Enumeration keys = req.getParameterNames();//取出客戶端傳入的所有參數名
ArrayList<String> params = new ArrayList<String>();
String url=null;
while (keys.hasMoreElements()){
String key = (String) keys.nextElement();
params.add(key);//其它加入參數列表,此處為參與遠程請求的參數
requestType = true;//修改標記,表求遠程請求為POST方式
}
HttpClient client = new HttpClient();
HttpMethod method = null;
if(requestType){//判斷請求方式,並實例化HttpMethod對象,true:POST,false:GET
method = new UTF8PostMethod(url);
for(String name : params){//迭代POST參數,加入到請求中
String _value = req.getParameter(name);
((PostMethod)method).setParameter(name,_value);
}
}else{
method = new GetMethod(url);
}
client.executeMethod(method);//執行請求
String bodystr = method.getResponseBodyAsString();//返回結果
out.println(bodystr);//將結果返回給客戶端
}
/**
* 內部類,轉換URL字符串為UTF-8
* @author Administrator
*
*/
private static class UTF8PostMethod extends PostMethod {
public UTF8PostMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
return "UTF-8";
}
}