简体   繁体   English

从另一个servlet调用servlet

[英]Calling servlet from another servlet

I have two servlets which are running on different tomcat servers. 我有两个在不同的tomcat服务器上运行的servlet。

I and trying to call a servlet1 from servlet2 in the following way and wanted to write an object to output stream. 我并尝试通过以下方式从servlet2调用servlet1,并希望将一个对象写入输出流。

URL url=new URL("http://msyserver/abc/servlet1");
URLConnection con=url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
OutputStream os=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(pushEmailDTO);
oos.flush();
oos.close();

The problem is that i am unable to hit the servlet? 问题是我无法点击servlet? I cannot figure out what i am missing. 我无法弄清楚我所缺少的。

You must create a connection via url.connect() before you can read/send data. 必须先通过url.connect()创建连接,然后才能读取/发送数据。 This is counter-intuitive since the name openConnection() suggests that it does that already but the docs say: 这是违反直觉的,因为名称openConnection()表示已经做到了,但是文档说:

In general, creating a connection to a URL is a multistep process: 通常,创建到URL的连接是一个多步骤过程:

  1. openConnection()
  2. Manipulate parameters that affect the connection to the remote resource. 处理影响到远程资源连接的参数。
  3. connect() connect()
  4. Interact with the resource; 与资源互动; query header fields and contents. 查询标题字段和内容。

This is why getExpiration() makes it work: It calls connect() for you. 这就是getExpiration()使之起作用的原因:它为您调用connect()

What is the error you are getting? 您遇到什么错误? Check that the address is correct. 检查地址是否正确。 If the remote server is running in a port other than 80, then take this into consideration when building the URL. 如果远程服务器运行的端口不是80,则在构建URL时要考虑到这一点。

May also I suggest to use HttpClient instead of URLConnection. 我也可能建议使用HttpClient代替URLConnection。

I cannot unnderstand but it worked by adding the following line in the code. 我无法理解,但是通过在代码中添加以下行来起作用。

con.getExpiration();

like this 像这样

URL url=new URL("http://msyserver/abc/servlet1");
URLConnection con=url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.getExpiration();//<----------
OutputStream os=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(pushEmailDTO);
oos.flush();
oos.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM