Skip to content

Instantly share code, notes, and snippets.

@eugenp
Created January 29, 2012 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eugenp/1700837 to your computer and use it in GitHub Desktop.
Save eugenp/1700837 to your computer and use it in GitHub Desktop.
InfoQ - Building REST with Spring - the Web/Controller layer
@Controller
public class FooController{
@Autowired
IFooService service;
// API
@RequestMapping( value = "admin/foo",params = { "page", "size" },method = GET )
@ResponseBody
public List< Foo > findPaginated(
@RequestParam( "page" ) int page, @RequestParam( "size" ) int size,
UriComponentsBuilder uriBuilder, HttpServletResponse response ){
Page< Foo > resultPage = service.findPaginated( page, size );
if( page > resultPage.getTotalPages() ){
throw new ResourceNotFoundException();
}
eventPublisher.publishEvent( new PaginatedResultsRetrievedEvent< Foo >(
Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size ) );
return resultPage.getContent();
}
@RequestMapping( value = "foo",method = RequestMethod.GET )
@ResponseBody
public List< Foo > getAll(){
return service.getAll();
}
@RequestMapping( value = "foo/{id}",method = RequestMethod.GET )
@ResponseBody
public Foo get( @PathVariable( "id" ) Long id ){
return RestPreconditions.checkNotNull( service.getById( id ) );
}
@RequestMapping( value = "foo",method = RequestMethod.POST )
@ResponseStatus( HttpStatus.CREATED )
@ResponseBody
public Long create( @RequestBody Foo entity ){
RestPreconditions.checkNotNullFromRequest( entity );
return service.create( entity );
}
@RequestMapping( value = "foo",method = RequestMethod.PUT )
@ResponseStatus( HttpStatus.OK )
public void update( @RequestBody Foo entity ){
RestPreconditions.checkNotNullFromRequest( entity );
RestPreconditions.checkNotNull( service.getById( entity.getId() ) );
service.update( entity );
}
@RequestMapping( value = "foo/{id}",method = RequestMethod.DELETE )
@ResponseStatus( HttpStatus.OK )
public void delete( @PathVariable( "id" ) Long id ){
service.deleteById( id );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment