springmvc 接收application/json和application/xml请求体

预备知识

什么是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>
                
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                
                <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;
}

其他

Servlet接收application/json和application/xml请求体

你可能感兴趣的:(java,spring)