Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

java - doGet and doPost String = null issue

I am trying to send String to server(running on tomcat) and have it return the String. The client sends the string, the server recieves it, but when the client gets it back the String is null.

doGet() should set String in = input from client. But doPost() is sending String in = null.

Why? I would assume that doGet() runs before doPost() because it is being called first by the client.

Server:

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){

    }
}

Client:

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to read an arbitrary String from a client (or send it back), then you want to just read and write the String directly: there is no need to use ObjectInputStream and ObjectOutputStream. Like this:

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

If you want to be able to echo the string back to a client (but also protect the data from others), then you should use an HttpSession. If this is supposed to be some kind of "echo" service where you want any client to be able to set the string value and then all clients get the same one back, then you should not use HttpSession and instead use an instance-scoped reference as you have above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...