Java Web 服务: Axis2 中的 JAXB 和 JAX-WS
2009-11-05 00:00:00 来源:WEB开发网如果上一步骤成功,那么尝试使用相同 ISBN 添加另一本书(这个操作应当永远都是失败的)。
获得有关某一特定类型的所有图书的信息。
清单 2 展示了完整的测试客户机代码。可以看到用于每个操作的封装器对象中的服务接口的封装特性,比如调用 getTypes 操作所需的 GetTypes 对象(即使没有为该操作提供输入数据)和由调用返回的 GetTypesResponse 对象。
清单 2. JAXB 测试客户机代码
public class WebServiceClient
{
public static void main(String[] args) throws Exception {
// check for required command line parameters
if (args.length < 3) {
System.out.println("Usage:\n java " +
"com.sosnoski.ws.library.jaxb.WebServiceClient host port path");
System.exit(1);
}
// create the client stub
String target = "http://" + args[0] + ":" + args[1] + args[2];
System.out.println("Connecting to " + target);
JaxbLibraryStub stub = new JaxbLibraryStub(target);
// retrieve a book directly
String isbn = "0061020052";
GetBook gb = new GetBook();
gb.setIsbn(isbn);
GetBookResponse gbr = stub.getBook(gb);
BookInformation book = gbr.getGetBookReturn();
if (book == null) {
System.out.println("No book found with ISBN '" + isbn + '\'');
} else {
System.out.println("Retrieved '" + book.getTitle() + '\'');
}
// retrieve the list of types defined
GetTypesResponse gtr = stub.getTypes(new GetTypes());
List<TypeInformation> types = gtr.getGetTypesReturn();
System.out.println("Retrieved " + types.size() + " types:");
for (int i = 0; i < types.size(); i++) {
TypeInformation type = types.get(i);
System.out.println(" '" + type.getName() + "' with " +
type.getCount() + " books");
}
// add a new book
String title = "The Dragon Never Sleeps";
isbn = "0445203498";
try {
AddBook ab = new AddBook();
ab.setType("scifi");
ab.setIsbn(isbn);
ab.getAuthor().add("Cook, Glen");
ab.setTitle(title);
stub.addBook(ab);
System.out.println("Added '" + title + '\'');
title = "This Should Not Work";
ab.setTitle(title);
stub.addBook(ab);
System.out.println("Added duplicate book - should not happen!");
} catch (AddDuplicateFault e) {
System.out.println("Failed adding '" + title +
"' with ISBN '" + isbn + "' - matches existing title '" +
e.getFaultMessage().getBook().getTitle() + '\'');
}
// get all books of a type
GetBooksByType gbbt = new GetBooksByType();
gbbt.setType("scifi");
GetBooksByTypeResponse gbbtr = stub.getBooksByType(gbbt);
List<BookInformation> books = gbbtr.getGetBooksByTypeReturn();
System.out.println("Retrieved " + books.size() + " books of type 'scifi':");
for (int i = 0; i < books.size(); i++) {
System.out.println(" '" + books.get(i).getTitle() + '\'');
}
}
}
更多精彩
赞助商链接