As you probably already know, Jersey uses MessageBodyWriters and MessageBodyReaders to parse incoming request and create outgoing responses. Every user can create its own representation but... this is not recommended way how to do things. XML is proven standard for interchanging information, especially in web services. Jerseys supports low level data types used for direct manipulation and JAXB XML entities.

Low level XML support

Jersey currently support several low level data types: StreamSourceSAXSourceDOMSource and Document. You can use these types as return type or method (resource) parameter. Lets say we want to test this feature and we have helloworld sample as starting point. All we need to do is add methods (resources) which consumes and produces XML and types mentioned above will be used.

@Path("1")
@POST
public StreamSource get1(StreamSource streamSource) {
return streamSource;
} @Path("2")
@POST
public SAXSource get2(SAXSource saxSource) {
return saxSource;
} @Path("3")
@POST
public DOMSource get3(DOMSource domSource) {
return domSource;
} @Path("4")
@POST
public Document get4(Document document) {
return document;
}

Both MessageBodyReaders and MessageBodyWriters are used in this case, all we need is do POST request with some XML document as a request entity. I want to keep this as simple as possible so I'm going to send only root element with no content: "<test />". You can create Jersey client to do that or use some other tool, for example curl as I did. (curl -v http://localhost:9998/helloworld/1 -d "<test />"). You should get exactly same XML from our service as is present in the request; in this case, XML headers are added to response but content stays. Feel free to iterate through all resources.

Getting started with JAXB

Good start for people which already have some experience with JAXB annotations is JAXB sample. You can see various usecases there. This text is mainly meant for those who don't have prior experience with JAXB. Don't expect that all possible annotations and their combinations will be covered in this chapter, JAXB (JSR 222 implementation) is pretty complex and comprehensive. But if you just want to know how you can interchange XML messages with your REST service, you are looking at right chapter.

Lets start with simple example. Lets say we have class Planet and service which produces "Planets":

// Planet class
@XmlRootElement
public class Planet {
public int id;
public String name;
public double radius;
} // Resource class
@Path("planet")
public class Resource { @GET
@Produces(MediaType.APPLICATION_XML)
public Planet getPlanet() {
Planet p = new Planet();
p.id = 1;
p.name = "Earth";
p.radius = 1.0; return p;
}
}

You can see there is some extra annotation declared on Planet class. Concretely XmlRootelement. What it does? This is a JAXB annotation which maps java class to XML element. We don't need specify anything else, because Planet is very simple class and all fields are public. In this case, XML element name will be derived from class name or you can set name property: @XmlRootElement(name="yourName").

Our resource class will respond to GET /planet with

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
<id>1</id>
<name>Earth</name>
<radius>1.0</radius>
</planet>

which might be exactly what we want... or not. Or we might not really care, because we can use Jersey client for making requests to this resource and this is easy as: Planet planet = webResource.path("planet").accept(MediaType.APPLICATION_XML_TYPE).get(Planet.class);. There is pre-created WebResource object which points to our applications context root and we simpli add path (in our clase its "planet"), accept header (not mandatory, but service could provide different content based on this header; for example text/html can be served for web browsers) and at the end we specify that we are expecting Planet class via GET request.

There may be need for not just producing XML, we might want to consume it as well.

@POST
@Consumes(MediaType.APPLICATION_XML)
public void setPlanet(Planet p) {
System.out.println("setPlanet " + p);
}

After valid request is made (with Jersey client you can do webResource.path("planet").post(p);), service will print out string representation of Planet, which can look like Planet{id=2, name='Mars', radius=1.51}.

If there is a need for some other (non default) XML representation, other JAXB annotations would need to be used. This process is usually simplified by generating java source from XML Schema which is done by xjc. Xjc is XML to java compiler and is part of JAXB. See JAXB home page for further details.

POJOs

Sometimes you can't / don't want to add JAXB annotations to source code and you still want to have resources consuming and producing XML representation of your classes. In this case, JAXBElement class should help you. Let's redo planet resource but this time we won't have XmlRootElement annotation on Planet class.

@Path("planet")
public class Resource { @GET
@Produces(MediaType.APPLICATION_XML)
public JAXBElement<Planet> getPlanet() {
Planet p = new Planet();
p.id = 1;
p.name = "Earth";
p.radius = 1.0; return new JAXBElement<Planet>(new QName("planet"), Planet.class, p);
} @POST
@Consumes(MediaType.APPLICATION_XML)
public void setPlanet(JAXBElement<Planet> p) {
System.out.println("setPlanet " + p.getValue());
}
}

As you can see, everything is little more complicated with JAXBElement. This is because now you need to explicitly set element name for Planet class XML representation. Client side is even more ugly than server side because you can't do JAXBElement<Planet>.class so Jersey client API provides way how to workaround it by declaring subclass of GenericType.

// GET
GenericType<JAXBElement<Planet>> planetType = new GenericType<JAXBElement<Planet>>() {}; Planet planet = (Planet) webResource.path("planet").accept(MediaType.APPLICATION_XML_TYPE).get(planetType).getValue();
System.out.println("### " + planet); // POST
Planet p = new Planet();
// ... webResource.path("planet").post(new JAXBElement<Planet>(new QName("planet"), Planet.class, p));

Using custom JAXBContext

In some scenarios you can take advantage of using custom JAXBContext. Creating JAXBContext is expensive operation and if you already have one created, same instance can be used by Jersey. Other possible usecase for this is when you need to set some specific things to JAXBContext, for example set different classloader.

@Provider
public class PlanetJAXBContextProvider implements ContextResolver<JAXBContext> {
private JAXBContext context = null; public JAXBContext getContext(Class<?> type) {
if(type != Planet.class)
return null; // we don't support nothing else than Planet if(context == null) {
try {
context = JAXBContext.newInstance(Planet.class);
} catch (JAXBException e) {
// log warning/error; null will be returned which indicates that this
// provider won't/can't be used.
}
}
return context;
}
}

Sample above shows simple JAXBContext creation, all you need to do is put this @Provider annotated class somewhere where Jersey can find it. Users sometimes have problems with using provider classes on client side, so just for reminder - you have to declare them in client config (cliend does not anything like package scanning done by server).

ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(PlanetJAXBContextProvider.class);
Client c = Client.create(cc);

Jersey(1.19.1) - XML Support的更多相关文章

  1. Jersey(1.19.1) - JSON Support

    Jersey JSON support comes as a set of JAX-RS MessageBodyReader<T> and MessageBodyWriter<T&g ...

  2. Jersey(1.19.1) - Hello World, Get started with a Web application

    1. Maven Dependency <properties> <jersey.version>1.19.1</jersey.version> </prop ...

  3. Jersey(1.19.1) - Root Resource Classes

    Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path have at least ...

  4. Jersey(1.19.1) - Hello World, Get started with Jersey using the embedded Grizzly server

    Maven Dependencies The following Maven dependencies need to be added to the pom: <dependency> ...

  5. Jersey(1.19.1) - Deploying a RESTful Web Service

    JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and pro ...

  6. Jersey(1.19.1) - Building Responses

    Sometimes it is necessary to return additional information in response to a HTTP request. Such infor ...

  7. Jersey(1.19.1) - Sub-resources

    @Path may be used on classes and such classes are referred to as root resource classes. @Path may al ...

  8. Jersey(1.19.1) - Client API, Ease of use and reusing JAX-RS artifacts

    Since a resource is represented as a Java type it makes it easy to configure, pass around and inject ...

  9. Jersey(1.19.1) - Client API, Overview of the API

    To utilize the client API it is first necessary to create an instance of a Client, for example: Clie ...

随机推荐

  1. Rop 文件上传解决思路

    由于服务请求报文是一个文本,无法直接传送二进制的文件内容,因此必须采用某种转换机制将二进制的文件内容转换为字符串.Rop 采用如下的方式对上传文件进行编码:<fileType>@<B ...

  2. 转载 从Http到Https

    转载自 http://www.cnblogs.com/silin6/p/5928503.html HTTP 当你在浏览器输入一个网址 (例如 http://tasaid.com)的时候,浏览器发起一个 ...

  3. 转载JQuery 中empty, remove 和 detach的区别

    转载 http://www.cnblogs.com/lisongy/p/4109420.html .empty()  描述: 从DOM中移除集合中匹配元素的所有子节点. 这个方法不接受任何参数. 这个 ...

  4. Umbraco中的Examine Search功能讲解

    转载原地址: http://24days.in/umbraco/2013/getting-started-with-examine/ Everytime I read the word Examine ...

  5. UVaLive 7269 Snake Carpet (找规律,模拟)

    题意:给定一个数字n,表示有n条蛇,然后蛇的长度是 i ,如果 i 是奇数,那么它只能拐奇数个弯,如果是偶数只能拐偶数个,1, 2除外,然后把这 n 条蛇, 放到一个w*h的矩阵里,要求正好放满,让你 ...

  6. Unity3D之飞机游戏追踪导弹制作

    最近开发完成一款打飞机的游戏,记录一下制作追踪导弹的方法,最开始在网上找到的资料制作出来的追踪导弹都不够真实,主要的问题是没有对导弹进行一个阀值处理,导弹每帧都始终会面向目标,而不是按照一定的角度进行 ...

  7. Java数据库编程(JDBC)

    一.使用Java对数据库的操作步骤: 1.根据应用程序的数据库类型,加载相应的驱动: 2.连接到数据库,得到Connection对象: 3.通过Connection创建Statement对象: 4.使 ...

  8. jsp验证码点击刷新

    <img src="<%=basePath%>manage/code" alt="验证码" height="20" ali ...

  9. stm32上的Lava虚拟机开发进度汇报(1)

    这几天我打算在stm32上做一个lava的虚拟机,只要160*80的黑白显示就行了,主要是想怀旧一下,嘿嘿. 目前的进度是图形显示和按键处理完成了,还有文本显示.文件处理.其他函数等. 当然,这都仅是 ...

  10. Codeforces Testing Round #12 B. Restaurant 贪心

    B. Restaurant Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/597/problem ...