Reputation: 61
I am having trouble connecting all the pieces that would allow xml sent from an ajax client to be unmarshalled into Java objects. I am using Jquery for the ajax client, Spring3, and JAXB. Here are the key components:
Ajax Client
function checkForNewActivities(activities) {
$j.ajax({
url: "upload/checkForNewActivities",
type: "POST",
async: true,
dataType: "xml",
data: ({activities:activities}),
contentType: "application/xml",
beforeSend: function() {
alert("sending ajax");
},
complete: function() {
alert("ajax sent");
},
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + errorThrown);
}
});
}
Spring Config
<bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller" />
<property name="unmarshaller" ref="jaxbMarshaller" />
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
a bunch of java classes
</list>
</property>
</bean>
And here is the Spring Controller method that is the target:
@RequestMapping(value="/checkForNewActivities",headers="application/xml", method=RequestMethod.POST)
public @ResponseBody String uploadMultipleWorkouts(@RequestBody String activities) {
System.out.println(activities);
return "";
}
With the headers="application/xml" in the RequestMapping, this method never gets called. If I remove the headers param, then the method is called and dumping the activities to the console shows the escaped xml.
I am clearly missing how to connect this method to the spring config so that unmarshalling xml takes place.
Upvotes: 3
Views: 579
Reputation: 2066
The reason your println prints out escaped xml is because the data type of the variable activities
is String
. You'll want to create a class to hold that data which will be passed to the method so there is a structure into which JAXB may translate the xml.
For example, instead of
public @ResponseBody String uploadMultipleWorkouts(@RequestBody String activities) {
You would want
public @ResponseBody Activities uploadMultipleWorkouts(@RequestBody Activities activities) {
Where Activities
is a class you have defined with appropriate getters and setters such that the xml data you're passing in can be assigned. If the request data and response data must be different then you can simply define two classes, Request and Response variants.
As for why using headers="application/xml"
messes things up, try setting it to headers = {"content-type=application/xml"}
Upvotes: 2