Spring-boot return json and xml from controllers

前端 未结 8 1496
Happy的楠姐
Happy的楠姐 2020-12-16 12:05

I have a spring-boot 1.1.7 application that uses Thymeleaf for much of the UI, so the response from my controllers hasn\'t really been a concern. However, now I need to pro

8条回答
  •  庸人自扰
    2020-12-16 12:51

    It may be better to create a new class:

    public class SdnSearchResult {
      private List sdns;
      ...
    }
    

    Then, a slight change will be required to the existing classes as follows:

    public interface SdnSearchService {
      SdnSearchResult find(SdnSearch sdnSearch);
    }
    
    @Controller
    public class UISearchController {
      @Autowired
      private SdnSearchService sdnSearchService;
    
      @RequestMapping("/search")
      public ModelAndView search(@ModelAttribute SdnSearch sdnSearch) {
        return new ModelAndView("pages/search/results", "sdns", sdnSearchService.find(sdnSearch).getSdns());
      }
    }
    

    Once this is done, the other controller must be coded as:

    @Controller
    public class RemoteSearchController {
      @Autowired
      private SdnSearchService sdnSearchService;
    
      @RequestMapping("/remote/search")
      @ResponseBody
      public SdnSearchResult search(@RequestBody SdnSearch sdnSearch) {
        return sdnSearchService.find(sdnSearch);
      }
    }
    

    A quick explanation of the changes from your code:

    1. @RequestBody will automatically deserialize the entire HTTP request body to an SdnSearch instance. External applications will typically submit the request data as HTTP body, so @RequestBody will ensure that the deserialization to Java object happens automatically.
    2. @ResponseBody will automatically serialize the return value according to the external client's capabilities and the libraries available on the classpath. If Jackson is available on the classpath and the client has indicated that they can accept JSON, the return value will be automatically sent as JSON. If the JRE is 1.7 or higher (which means that JAXB is included with the JRE) and the client has indicated that they can accept XML, the return value will be automatically sent as XML.
    3. List needs to be changed to SdnSearchResult to ensure that the application can exchange JSON, XML, RSS and ATOM formats with a single controller method, since XML (and XML based formats) require a root-tag on the output, which a List cannot be translated to.

    Once these changes are done, fire up a REST client such as the Postman extension for Chrome and submit a request to /remote/search with the following information:

    1. Request header Accepts set to application/json.
    2. Request header Content-Type set to application/json.
    3. Request body set to the JSON string { "sdnName" : "Victoria", "address" : "123 Maple Ave" }.

    This will give you a JSON response.

提交回复
热议问题