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";
}
}