开发者

Adding links to REST Responses

I have REST services that respond with unmarshalled domain entities. For example:

Request:
GET http://someAddress.com/customer/001

Response:
<customer>
    <id>001<开发者_如何学JAVA;/id>
    <name>Some Guy</name>
    ...
</customer>

I would like to add some links to the response for discovering services. For example:

<customer>
    <id>001</id>
    <name>Some Guy</name>
    ...
    <link xml:link="delete" href="http://someAddress.com/customer/001"/>
</customer>

The concern I have is if this will cause marshalling problems. I want the links discoverable, but I want consumers to use the domain schema easily, which does not contain elements for links.

Is it better to put the links elsewhere in the reply? If so, where?


Assuming you are using JAXB for the object-to-XML layer you could do something like the following with an XmlAdapter, but instead of a String you will need an object for Link:

import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class CustomerAdapter  extends XmlAdapter<String, Customer>{

    private JAXBContext jaxbContext;

    public CustomerAdapter() {
        try {
            jaxbContext = JAXBContext.newInstance(Customer.class);
        } catch(JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String marshal(Customer v) throws Exception {
        if(null == v) {
            return null;
        }
        return "http://someAddress.com/customer/" + v.getId();
    }

    @Override
    public Customer unmarshal(String v) throws Exception {
        if(null == v) {
            return null;
        }

        URL url = new URL(v);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");

        Customer customer = (Customer) jaxbContext.createUnmarshaller().unmarshal(connection.getInputStream());
        connection.disconnect();
        return product;
    }

}

For more information on XmlAdapter see:

  • http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html


If you really don't want to change your schemas to support the link element then you could use Link headers. https://www.rfc-editor.org/rfc/rfc5988

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜