Get XML from HttpServletRequest and use into endpoint

后端 未结 2 399
花落未央
花落未央 2021-01-17 01:33

I would like to get the XML data from request and response and use it into Rest controller. I tried this:

@RestController()
    public class HomeController {         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 02:17

    You dont need to do anything special here, Spring framework will do it for you. All you need is:

    1. Create a Pojo or Bean which represents your XML data.

    2. Add xml data format dependency to Gradle/Maven which will bind the request xml to your pojo.

       compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.9.9'
      
    3. Tell your request handler to accept XML like this:

      @RequestMapping(value = "/xmlexample", method = RequestMethod.POST,consumes = "application/xml;charset=UTF-8") 
      public final boolean transactionHandler(@Valid @RequestBody Transaction transaction) {
          log.debug("Received transaction request with data {}", transaction);
          return true;
      }
      

    And voila, you will have your transaction bean populated with your XML data.

提交回复
热议问题