Hypermedia with Jersey using Atom

a 夏天 提交于 2019-12-05 02:19:09

问题


Every book on REST uses <atom:link href="..." rel="..."> to define Hypermedia in RESTful apps; but Jersey (with the use of JAXB) do not seems to have this support.

I've tried @XmlSchema in package-info.java as explained here; I've also tried extendingNamespacePrefixMapper as explained there. But none works and output this at best:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer xmlns:ns2="http://www.w3.org/2005/Atom">
    <first-name>Roland</first-name>
    <ns2:link href="/customer/1" rel="self" />
</customer>

Using namespace and, as a result, Atom, seems impossible in Jersey. I've miss something?

ps. I'me using a XSD to generate @XmlElement classes, and, for the moment, I create my own Link class. Is there a schema or a JAR to do that (jersey-atom maven dependency uses rome but without any help)


回答1:


(Assuming that you are not concerned with the namespace prefix and just want to create the links)

Here is my approach to creating the links. In my resource class (the jersey rest service), I return a java object (below "Person"), whose class is decorated with jaxb annotations. One of the properties returns atom link objects.

@XmlRootElement(namespace = Namespace.MyNamespace)
public class Person implements Serializable {
    private AtomLinks links = null;

    @XmlElement(name = "link", namespace = Namespace.Atom)
    public AtomLinks getLink() {
        if (this.links == null) {
            this.links = new AtomLinks();
        }

        return this.links;
    }
..
}

@XmlAccessorType(value = XmlAccessType.NONE)
public class AtomLinks extends ArrayList<AtomLink> {
..
}

@XmlAccessorType(value = XmlAccessType.NONE)
public class AtomLink implements Serializable {
    @XmlAttribute(name = "href")
    public URI getHref() {
        return href;
    }
    @XmlAttribute(name = "rel")
    public String getRel() {
        return rel;
    }
    @XmlAttribute(name = "type")
    public String getType() {
        return type;
    }
    @XmlAttribute(name = "hreflang")
    public String getHreflang() {
        return hreflang;
    }
    @XmlAttribute(name = "title")
    public String getTitle() {
        return title;
    }
..
}

public class Namespace {
    public final static String Atom = "http://www.w3.org/2005/Atom";
..
}

Prior to returning my object ("Person") I fill in the links, creating a self link and links to other related links. I utilize the uriInfo object that jersey injects to get the base url. If this is helpful but you would like more of the example, let me know and I will fill in the gaps.




回答2:


If I am right there is an approach in Jersey to inject the links to the objects.

See: Jersey 2.9 User Guide Chapter 6.



来源:https://stackoverflow.com/questions/6087382/hypermedia-with-jersey-using-atom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!