为了方便服务端与客户端之间相互传输复杂的对象。 我们可以先将对象的定义使用schema(.xsd文件)定义好。然后将.xsd文件转换为java对象再通过Jaxb工具包来进行操作。
加入org.restlet.ext.jaxb.jar
第一步:定义对象Movie.xsd
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/Mail" xmlns:tns="http://www.example.org/Mail" elementFormDefault="qualified"> <complexType name="Movie"> <sequence> <element type="string" name="name" /> <element type="long" name="size" /> <element type="int" name="minutes" /> </sequence> </complexType> </schema>
注意:然后打开Movie.java类,在类名上面加入@XmlRootElement注解
第三步:编写服务端资源
@Get public Representation getMovieInfo() throws IOException{ Movie movie = new Movie() ; movie.setName("速度与激情6"); movie.setSize(100000l); movie.setMinutes(120); //将movie对象包装成为一个JaxbRepresentation并返回 JaxbRepresentation<Movie> result = new JaxbRepresentation<Movie>(movie); return result ; }
第四步:启动服务器,并使用浏览器访问http://localhost:8888,将会看到Movie对象的xml形式输出
第五步:使用restlet支持开发客户端
@Test public void test02() throws IOException{ ClientResource client = new ClientResource("http://localhost:8888/"); //获取返回结果 Representation result = client.get() ; //包装为JaxbRepresentation , 注意:这里不能直接将result强制转换为JaxbRepresentation类型 JaxbRepresentation<Movie> jr = new JaxbRepresentation<Movie>(result,Movie.class) ; Movie movie = jr.getObject() ; System.out.printf("name:%s size:%d minuts:%d" , movie.getName() , movie.getSize() ,movie.getMinutes()); }
name:速度与激情6 size:100000 minuts:120
也可以不先定义.xsd文件,而直接编写Movie.java对象。但是就要手动加上必要的注解了。
使用.xsd文件的另一个好处是对服务器端与客户端的相互传输的对象的约束。该文件可以提供给客户端,客户端就可以根据.xsd文件知道我们要接受或返回的是个什么类型的对象了。