springmvc 接收application/json和application/xml请求体
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
预备知识
什么是application/json和application/xml?
https://imququ.com/post/four-ways-to-post-data-in-http.html
环境
Spring3
jackson-core-2.0.5.jar
jackson-annotations-2.0.5.jar
jackson-mapper-lgpl-1.9.0.jar
jackson-core-lgpl-1.9.0.jar
jackson-databind-2.0.5.jar
Spirng配置
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
<list>
<!--解析json-->
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<!--解析xml-->
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
</list>
</property>
</bean>
@RequstBody讲解
该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
摘自:https://blog.csdn.net/walkerjong/article/details/7946109
Controller配置
JSON
import net.sf.json.JSONObject;
@RequestMapping(value = "/xx")
@ResponseBody
public void json(@RequestBody JSONObject json){
//TODO 业务逻辑
}
XML
import javax.xml.transform.dom.DOMSource;
@RequestMapping(value = "/xx")
@ResponseBody
public void xml(@RequestBody DOMSource domsource){
String xml = parseDOMSource(domsource);
//TODO 业务逻辑
}
public String parseDOMSource(DOMSource domsource) {
try {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domsource, result);
return writer.toString();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
其他
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
4 个月前
8c391e04
7 个月前
更多推荐
已为社区贡献6条内容
所有评论(0)