Jayyrus
Jayyrus

Reputation: 13051

How to transfer object between client and webservice rest using jersey and java

i'm new in JAX-WS and i've created a test sample like:

SERVER:

@Path("/login")
public class Login {
   public Login(){
      initDB();
   }
    @GET
    @Path("{username}/{password}")  
    @Produces(MediaType.TEXT_PLAIN)
    public String login(@PathParam("username") String username,@PathParam("password") String password) {
     int id = db.login(username, password);
     return ""+id;
    }
} 

CLIENT:

public class WSConnection {

    private ClientConfig config;
    private Client client;
    private WebResource service;
    public WSConnection(){
        config = new DefaultClientConfig();
        client = Client.create(config);
        service = client.resource(getBaseURI());
    }
    public int login(String username,String password){
        return Integer.parseInt(service.path("rest").path("login").path(username).path(password).accept(
                MediaType.TEXT_PLAIN).get(String.class));
    }
    private URI getBaseURI() {
        return UriBuilder.fromUri(
                "http://localhost:8080/Project2").build();
    }
}

In server, on method login, i return the id of the user selected from username and password. If i want to return the object:

public class Utente {

    private int id;
    private String username;
    private String nome;
    private String cognome;

    public Utente(int id, String username, String nome, String cognome) {
        this.id = id;
        this.username = username;
        this.nome = nome;
        this.cognome = cognome;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getCognome() {
        return cognome;
    }
    public void setCognome(String cognome) {
        this.cognome = cognome;
    }   
}

What i have to do? can someone explain me ? thank you!!! :)

Upvotes: 1

Views: 1790

Answers (1)

Martin Matula
Martin Matula

Reputation: 7979

Annotate your object with @XmlRootElement and change @Produces(MediaType.TEXT_PLAIN) on your resource to @Produces(MediaType.APPLICATION_XML). Return that object from the resource method - it will get automatically sent as XML to the client. On the client side you can do:

Utente u = service.path("rest").path("login").path(username).path(password)
           .accept(MediaType.APPLICATION_XML).get(Utente.class);

Btw, it is a bad idea to map login operation to HTTP GET - you should use POST instead.

Upvotes: 4

Related Questions