Accepting / returning XML/JSON request and response - Spring MVC

前端 未结 5 837
無奈伤痛
無奈伤痛 2021-01-31 04:54

I need to write a rest service which accepts XML/JSON as a input (POST method) and XML/JSON as a output (based on the input format). I have tried a below approach to achieve thi

5条回答
  •  感动是毒
    2021-01-31 05:36

    The best practice for handling different data formats with the same controller is to let the framework do all the work of figuring out the marshalling and unmarshalling mechanisms.

    Step 1: Use minimal controller configuration

    @RequestMapping(value = "/getxmljson", method = RequestMethod.POST)
    @ResponseBody
    public Student processXMLJsonRequest(@RequestBody Student student) {
      return student;
    }
    

    There is no need to specify consumes and produces here. As an example, consider that you may want this same method to handle other formats in the future such as Google Protocol Buffers, EDI, etc. Keeping the controllers free of consumes and produces will let you add data formats through global configuration instead of having to modify the controller code.

    Step 2: Use ContentNegotiatingViewResolver instead of RequestMappingHandlerAdapter

      
        
          
            
          
        
      
    

    Let the view resolver decide how to read incoming data and how to write it back.

    Step 3: Use Accepts and Content-Type HTTP headers

    Hitting your controller with the correct HTTP header values will force ContentNegotiatingViewResolver to marshal and unmarshal data automatically using the appropriate data representations.

    If you want to exchange data in JSON format, set both headers to application/json. If you want XML instead, set both to application/xml.

    If you do not want to use HTTP headers (which ideally you should), you can simply add .json or .xml to the URL and ContentNegotiatingViewResolver will do the rest.


    You can check out my sample app that I created using your code snippets that works fine for JSON and XML.

提交回复
热议问题