Skip to content

Instantly share code, notes, and snippets.

@danveloper
Created December 29, 2014 02:38
Show Gist options
  • Save danveloper/e234f99d12d997f504ee to your computer and use it in GitHub Desktop.
Save danveloper/e234f99d12d997f504ee to your computer and use it in GitHub Desktop.
Spring RestController PUT/Update
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public HttpEntity update(@PathVariable String id, HttpServletRequest request) throws IOException {
ProductDetail existing = find(id);
ProductDetail updated = objectMapper.readerForUpdating(existing).readValue(request.getReader());
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("productId", updated.getProductId());
propertyValues.add("productName", updated.getProductName());
propertyValues.add("shortDescription", updated.getShortDescription());
propertyValues.add("longDescription", updated.getLongDescription());
propertyValues.add("inventoryId", updated.getInventoryId());
DataBinder binder = new DataBinder(updated);
binder.addValidators(validator);
binder.bind(propertyValues);
binder.validate();
if (binder.getBindingResult().hasErrors()) {
return new ResponseEntity<>(binder.getBindingResult().getAllErrors(), HttpStatus.BAD_REQUEST);
} else {
return new ResponseEntity<>(updated, HttpStatus.ACCEPTED);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment