-1

我正在尝试将字符串发送到服务器(在 tomcat 上运行)并让它返回字符串。客户端发送字符串,服务器接收它,但是当客户端取回它时,字符串为空。

doGet() 应该设置 String in = 来自客户端的输入。但是 doPost() 在 = null 中发送字符串。

为什么?我会假设 doGet() 在 doPost() 之前运行,因为它是由客户端首先调用的。

服务器:

private String in = null;

public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
    try{
    ServletInputStream is = request.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);

    in = (String)ois.readObject();

    is.close();
    ois.close();
    }catch(Exception e){

    }
}

public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
    try{
    ServletOutputStream os = response.getOutputStream(); 
    ObjectOutputStream oos = new ObjectOutputStream(os); 

    oos.writeObject(in);
    oos.flush();

    os.close();
    oos.close();
    }catch(Exception e){

    }
}

客户:

URLConnection c = new URL("***********").openConnection();
c.setDoInput(true);
c.setDoOutput(true);

OutputStream os = c.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);

oos.writeObject("This is the send");
oos.flush();

InputStream is = c.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
System.out.println("return: "+ois.readObject());

ois.close();
is.close();
oos.close();
os.close();
4

1 回答 1

0

如果您想从客户端读取任意字符串(或将其发送回),那么您只想直接读取和写入字符串:不需要使用ObjectInputStreamand ObjectOutputStream。像这样:

public void doPost(...) {
  BufferedReader in = new BufferedReader(request.getReader());
  String s = in.readline();
  ...
}

如果您希望能够将字符串回显给客户端(同时也保护数据不被其他人访问),那么您应该使用HttpSession. 如果这应该是某种“回声”服务,您希望任何客户端都能够设置字符串值,然后所有客户端都返回相同的值,那么您不应该使用HttpSession而是使用实例范围的引用作为你有上面。

于 2013-08-10T13:41:14.297 回答