Instead of transforming XML to and from native Java types in a tedious manner, you can leverage the advantages of using JAXB objects. Even though you can use the javax.xml.transform.Source, java.io.InputStream, or java.lang.String interfaces or even a simple byte array to store the XML either as a request or response entity, JAXB enables easier data binding
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="note")
@XmlType
public class Note {
private Long id;
private String text;
public Note() {
}
public Note(Long id, String text) {
this.id = id;
this.text = text;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement(name="notes")
public class NotesList {
@XmlElement(name="note")
private List<note> notes = new ArrayList<note>();
public NotesList() {
}
@XmlTransient
public List getNotes() {
return notes;
}
public void setNotes(List notes) {
this.notes = notes;
}
}
@Path("/hello")
public class HelloResource {
@Path("/notes")
@GET
public NotesList list() {
List listOfNotes = new ArrayList();
listOfNotes.add(new Note(1L,"one"));
listOfNotes.add(new Note(2L,"two"));
NotesList response = new NotesList();
response.getNotes().addAll(listOfNotes);
return response;
}
}
You could write a client or test it using a tool like Advanced Rest client chrome extension.
By default, the JAX-RS runtime environment attempts to create and use a default JAXBContext class for JAXB classes. However, if the default JAXBContext class is not suitable, then you can supply a JAXBContext class for the application using a JAX-RS ContextResolver provider interface.
This scenario might occur because of complexities of the JAXB classes for the application. You must add the @Provider annotation to the class; for example:
//below example from IBM knowledge center
@Provider
public class MyContextResolver implements ContextResolver<jaxbcontext> {
public JAXBContext getContext(Class<?> aType) {
if(aType == Book.class) {
JAXBContext myContext = /* This statement creates create a JAXB Context. */
return myContext;
}
/* This method returns null for any types not understood.
If null is returned, other application supplied ContextResolver<jaxbcontext>
will be used if available */
return null;
}
}
Add this class to the set of classes to return in your application sub-class, just as you did with your resource classes.
No comments:
Post a Comment