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
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:
@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.@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.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:
Accepts set to application/json.Content-Type set to application/json.{ "sdnName" : "Victoria", "address" : "123 Maple Ave" }.This will give you a JSON response.