SpringMVC接收xml格式参数

问题

在对接银行过程中,银行回调时请求参数格式为xml,要求返回格式也为xml(CDATA包裹),利用SpringMVC该怎么处理。

测试

xml格式参数为:

<xml>
  <order_id>order_id>
  <sign>sign>
  <data>data>
  <uuid>uuid>
xml>

提供接受参数的对象

@Data //lombok注解,无需手动添加getter/setter
@XmlRootElement(name = "xml") 
@ToString //lombok注解,无需手动添加toString方法
public class XmlRequest {

    private String order_id;
    private String sign;
    private String data;
    private String uuid;
}

返回参数对象

@Data
@XmlRootElement(name = "xml")
public class XmlResponse {

    private String code;
    private String msg;

    public XmlResponse() {
    }

    public XmlResponse(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

处理xml格式参数接口

    /**
     * 处理xml格式参数
     *
     * @param xmlRequest
     * @return
     */
    @RequestMapping(value = "/handleXmlParam", produces = {"application/xml;charset=UTF-8"})
    @ResponseBody
    public String handleXmlParam(@RequestBody XmlRequest xmlRequest) throws Exception {
        logger.info("XmlRequest:{}", xmlRequest);
        XmlResponse response = new XmlResponse("1", "success");
        return ojbectToXmlWithCDATA(XmlResponse.class, response);
    }

    /**
     * Java对象转换为CDATA包裹XML
     *
     * @param clazz
     * @param obj
     * @return
     * @throws Exception
     */
    public static String ojbectToXmlWithCDATA(Class clazz, Object obj) throws Exception {

        JAXBContext context = JAXBContext.newInstance(clazz);
        // 配置OutputFormat处理CDATA
        OutputFormat of = new OutputFormat();
        of.setCDataElements(new String[]{"^code", "^msg"});
        of.setPreserveSpace(true);
        of.setIndenting(true);
        // 创建序列化
        ByteArrayOutputStream op = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(op, of);
        SAXResult result = new SAXResult(serializer.asContentHandler());
        Marshaller mar = context.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        mar.marshal(obj, result);

        return op.toString("utf-8");
    }

使用Postman模拟请求,响应也为xml格式

SpringMVC接收xml格式参数_第1张图片

日志打印XmlRequest对象,说明参数已经正常接收

XmlRequest:XmlRequest(order_id=m180702762500000201807031109358406949, sign=wxd2a1d0594082a206, data={"application_status":"review"}, uuid=123654978945)

你可能感兴趣的:(Troubleshooting)