我正在尝试收集所有表单数据并将其作为XML发送到Controller。此XML将进一步发送到后端,它将负责处理它
JAXBMarshaller期望定义一个bean来编组传入的xml。但我没有。
请求:
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
processData: false,
data: collectFormData1(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown:'+errorThrown);
}
});
return false;
});
function collectFormData1()
{
//$rootElement = $('<FormXMLDoxument/>');
xmlDoc = document.implementation.createDocument("", "", null);
root = xmlDoc.createElement($('form').attr('name'));
$('form').find('div.section').each(function(index, section) {
sectionElement = xmlDoc.createElement($(section).attr('name'));
//xmlDoc.appendChild(sectionElement);
$(section).find('input').each(function(i, field) {
fieldElement = xmlDoc.createElement($(field).attr('name'));
fieldText=xmlDoc.createTextNode($(field).val());
fieldElement.appendChild(fieldText);
sectionElement.appendChild(fieldElement);
});
root.appendChild(sectionElement);
});
xmlDoc.appendChild(root);
console.log((new XMLSerializer()).serializeToString(xmlDoc));
return xmlDoc;
}
控制器
@RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml"})
@ResponseBody public String handleSave(@RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);//prints the form xml
return "<response>Success</response>";
}
答案 0 :(得分:1)
这很可能是由于缺少可以编组/解组xml的HttpMessageConverter。
如果您还没有这样做,请添加spring-oxm
。
如果您正在使用类路径扫描,请在@EnableWebMvc
组件中使用@Configuration
如果没有,请在配置中添加<mvc:annotation-driven/>
以启用默认转换器。
http://hillert.blogspot.com/2011/01/rest-with-spring-contentnegotiatingview.html
<强>更新强>
尝试将produces={"application/xml"}
添加到@RequestMapping
。
如果它是一个需要作为响应体返回的简单xml字符串,则可以使用HttpServletResponse.getWriter(),如How to return a simple xml string from a form post in Spring MVC中所述,或返回包含xml的ResponseEntity<String>
。
@RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml"})
@ResponseBody public ResponseEntity<String> handleSave(@RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);//prints the form xml
return new ResponseEntity<String>("<response>Success</response>", HttpStatus.OK);
}