Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...