2012-06-01 66 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。