4.1. Low level XML support
4.2. Getting started with JAXB
4.3. POJOs
4.4. Using custom JAXBContext
实体类Planet:
(注意如下注解:
@XmlRootElement
)
package resource;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Planet {
private int id;
private String name;
private double radius;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
服务器端代码:
package cn.flyingsoft.restful;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import resource.Planet;
@Path("jaxb")
public class JAXBElementResource {
@GET
@Produces(MediaType.APPLICATION_XML)
public JAXBElement<Planet> getPlanet(){
Planet p = new Planet();
p.setId(1);
p.setName("earth");
p.setRadius(1.2);
return new JAXBElement<Planet>(new QName("planet"), Planet.class, p);
}
@POST
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public JAXBElement<Planet> getAndPost(
@QueryParam("param1") String param1,
Planet p
){
System.out.println("===server====" + param1);
System.out.println("=========server=======" + p.getId() + "|" + p.getName() + "|" + p.getRadius());
// Planet p = new Planet();
return new JAXBElement<Planet>(new QName("planet"), Planet.class, p);
}
}
客户端调用测试代码:
/**
* 发送及接收JAXBElement类型的参数
*/
public static void JAXBElementTest(){
//create a client
Client c = Client.create();
//create a web resource
WebResource webResource = c.resource("http://localhost:8080/RESTWebService_helloWorld/rest");
//GET
//接收JAXBElement类型的参数
GenericType<JAXBElement<Planet>> planetType = new GenericType<JAXBElement<Planet>>(){};
JAXBElement<Planet> element = webResource.path("jaxb").accept(MediaType.APPLICATION_XML).get(planetType);
Planet planet = element.getValue();
System.out.println("----JAXBElementTest----" + planet.getId() + "|" + planet.getName() + "|" + planet.getRadius());
//POST
Planet p = new Planet();
p.setId(100);
p.setName("AAA");
p.setRadius(1.111);
//传递JAXB参数对象:Planet
//发送JAXBElement类型的参数
webResource.path("jaxb").queryParam("param1", "vvv").post(new JAXBElement<Planet>(new QName("planet"), Planet.class, p));
}