1

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

私がしなければならないこと?誰かが私を説明できますか?ありがとうございました!!!:)

4

1 に答える 1

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

ところで、ログイン操作をHTTPGETにマップすることはお勧めできません。代わりにPOSTを使用する必要があります。

于 2012-06-08T12:15:16.303 に答える