Created
April 15, 2012 10:27
-
-
Save odrotbohm/2391765 to your computer and use it in GitHub Desktop.
Usage of @responsebody
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Controller | |
@RequestMapping("/persons") | |
class PersonController { | |
private final PersonRepository repository; | |
@Autowired | |
public PersonController(PersonRepository repository) { | |
Assert.notNull(repository); | |
this.repository = repository; | |
} | |
@RequestMapping(method = RequestMethod.GET) | |
@ResponseBody | |
public HttpEntity<List<PersonDto>> showPersons() { | |
List<PersonDto> persons = new ArrayList<PersonDto>(); | |
for (Person person : repository.findAll()) { | |
persons.add(convertToDto(person)); | |
} | |
return new ResponseEntity<List<PersonDto>>(persons, HttpStatus.OK); | |
} | |
@RequestMapping(value = "/{id}", method = RequestMethod.GET) | |
@RepsonseBody | |
public HttpEntity<Person> showPerson(@PathVariable Long id) { | |
Person person = repository.findOne(id); | |
return new ResponseEntity<PersonDto>(convertToDto(person), HttpStatus.OK); | |
} | |
@RequestMapping(value = "/{id}", method = RequestMethod.PUT) | |
@ResponseCode(HttpStatus.OK) | |
public HttpEntity<Void> updatePerson(@PathVariable Long id, @RequestBody PersonDto personDto) { | |
if (!repository.exists(id)) { | |
return new ReponseEntity(HttpStatus.NOT_FOUND); | |
} | |
repository.save(fromDto(personDto); | |
} | |
@RequestMapping(method = RequestMethod.POST) | |
@ResponseBody | |
public HttpEntity<Void> createPerson(@RequestBody PersonDto personDto) { | |
Person person = repository.save(fromDto(personDto)); | |
HttpHeaders headers = new HttpHeaders(); | |
headers.setLocation(createLocationFor(person)); | |
return new ResponseEntity<Void>(headers); | |
} | |
private PersonDto convertToDto(Person person) { | |
// convert to JAXB mapped object | |
} | |
private Person fromDto(PersonDto personDto) { | |
// transform DTO into domain object | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment