Spring-boot return json and xml from controllers

前端 未结 8 1519
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:44

    SOLUTION: I used a combination of both answers below (thank you very much!). I am posting here in case anyone else needs help.

    My modified controller:

    @Controller
    public class RemoteSearchController {
    
        @Autowired
        private SdnSearchService sdnSearchService;
    
        @RequestMapping(value = "/remote/search", method = RequestMethod.GET, produces = { "application/xml", "text/xml" }, consumes = MediaType.ALL_VALUE )
        @ResponseBody
        public SdnSearchResults search(@ModelAttribute SdnSearch sdnSearch) {
            List foundSdns = sdnSearchService.find( sdnSearch );
            SdnSearchResults results = new SdnSearchResults();
            results.setSdns( foundSdns );
            return results;
        }
    }
    

    And on my client, I set the request headers:

    Content-type: application/text Accept: text/xml I think ultimately the problem was that my client headers were not being set correctly, so I may not have had to make some of these changes. But I liked the idea of a SearchResults class containing a list of results:

    @XmlRootElement
    public class SdnSearchResults {
        private List sdns;
    ...
    }
    

提交回复
热议问题