简体   繁体   中英

how can i pass java object from server side to client side

can i pass java POJO class object to client side .
for example user send request to server "/user" . server should send response as User.java object

User.java class is

public class User {

private String name = null;
private String education = null;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getEducation() {
    return education;
}
public void setEducation(String education) {
    this.education = education;
}

}

As mr.icetea suggested you can serialize the java object to json and then pass it . You can do the serialization/deserialization using the jackson library : http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

There are many ways:

  1. You can use any of the JSON,XML,SOAP formats.

  2. Or you can use applet

  3. Rmi if using standalone java client.

There are two simple ways that I can think of:

  1. Use JAXB to convert the User object into an xml and back to transfer the data between client and server.
  2. Use GSON/Jackson to do the same with a JSON.

Either ways the XML/JSON will directly map to your Objects and are fairly easy to implement.

There are other ways but I assume that you are using a web service and these are best suited for it.

I had the same requirement, I used servlet to do that. If you can use servlet, you can take this reference.

Servlet side

ObjectInputStream objectStream = new ObjectInputStream(request.getInputStream());
User user = (User) objectStream.readObject();
objectStream .close();

Client side

User user = new User();
urlConnectionToTarget.setRequestMethod("POST");
urlConnectionToTarget.setDoOutput(true);
urlConnectionToTarget.setDoInput(true);
urlConnectionToTarget.setRequestProperty("Content-Type", "application/octet-stream");
urlConnectionToTarget.connect();
ObjectOutputStream servletObjectStream = new ObjectOutputStream(urlConnectionToTarget.getOutputStream());
servletObjectStream.writeObject(user);
servletObjectStream.flush();
servletObjectStream.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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