I want to return a string (json string) from a spring controller as response to AJAX call it receives, the response could different based on whether or not I have a @Valid form submitted. This is how I am handling it and wanted to find out if this is considered as best practice? Please note I am using @RestController so @ResonseBody applies all methods.
@RequestMapping(value = "/save" , method = RequestMethod.POST)
public String saveScheduledAlert(@Valid ScheduledAlertForm scheduledAlertForm, BindingResult bindingResult) {
StringBuilder jsonString = new StringBuilder();
if(bindingResult.hasErrors()){
jsonString.append("{\"success\" : \"false\"");
for(ObjectError error : bindingResult.getAllErrors())
jsonString.append(",\"").append(((FieldError) error).getField()).append("\":\"").append(error.getDefaultMessage()).append("\"");
} else {
//save the data
jsonString.append("{\"success\" : \"true\"");
}
jsonString.append("}");
return jsonString.toString();
}