首页 / 操作系统 / Linux / 跨域Servlet调用Servlet的实现
跨域Servlet调用Servlet的实现跨域后,Servlet容器之间彼此是未知的环境,也不能获取到对方的ServetContext。因此使用内部跳转和重定向(需要带请求参数)调用都是错误的,也是无效的。通过HttpClinet模拟发起请求,可以实现跨域Servlet调用Servlet。实现方法:在Servlet的service方法中创建httpclient对象,来发起第二次请求。将请求转发个另一个域的servlet。public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //todo:执行第一个请求的处理 ....... //发出第二次请求,调用第二个Servert:postRemotetUrl
//建立HTTP请求
HttpClient httpClient = new DefaultHttpClient();
//注册证书
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
//设置请求超时时间
httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 20000);
//设置连接超时时间
httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
//建立POST请求
HttpPost httpPost = new HttpPost(postRemotetUrl);
httpPost.setEntity(new StringEntity(msg)); //提交httppost请求
HttpResponse httpResp = httpClient.execute(httpPost);
httpClient.getConnectionManager().shutdown();
.......}相关阅读:配置Struts2后如何使用Servlet http://www.linuxidc.com/Linux/2012-12/75823.htmAndroid通过http传输文件到Servlet http://www.linuxidc.com/Linux/2013-01/78240.htmServlet 调用 Spring 容器的 service http://www.linuxidc.com/Linux/2012-06/63007.htm使用 Spring 容器管理 Servlet http://www.linuxidc.com/Linux/2012-06/63008.htmWAS Websphere下新增Servlet无法访问的问题 http://www.linuxidc.com/Linux/2012-06/62805.htm