簡體   English   中英

如何使用jersey和java在客戶端和Web服務休息之間傳輸對象

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

我是JAX-WS的新手,我創建了一個測試樣本,如:

服務器:

@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;
    }
} 

客戶:

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();
    }
}

在服務器中,在方法登錄時,我返回從用戶名和密碼中選擇的用戶的id。 如果我想返回對象:

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;
    }   
}

我該怎么辦? 有人可以解釋一下嗎? 謝謝!!! :)

使用@XmlRootElement注釋對象並將資源上的@Produces(MediaType.TEXT_PLAIN)更改為@Produces(MediaType.APPLICATION_XML)。 從資源方法返回該對象 - 它將自動作為XML發送到客戶端。 在客戶端,您可以:

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

順便說一句,將登錄操作映射到HTTP GET是一個壞主意 - 你應該使用POST。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM