小编典典

doGet和doPost String = null问题

tomcat

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

doGet()应该将String in =从客户端输入。但是doPost()在= null中发送String。

为什么?我假设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();

阅读 513

收藏
2020-06-16

共1个答案

小编典典

如果要从客户端读取任意String(或将其发送回),则只想直接读取和写入String:无需使用ObjectInputStreamObjectOutputStream。像这样:

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

如果您希望能够将字符串回显给客户端(但也可以保护数据免受他人攻击),则应使用HttpSession。如果这是某种“回声”服务,您希望任何客户端都可以设置字符串值,然后所有客户端都返回相同的字符串,那么您不应该HttpSession使用实例范围的引用作为替代你有以上。

2020-06-16