2012-06-01 67 views
1

我在JAX-WS是新的客戶端和互聯網服務休息之間傳輸對象,我創建了一個測試樣本,如:如何使用的球衣和Java

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

客戶:

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

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

回答

4

使用@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。