Created
January 29, 2012 21:40
-
-
Save eugenp/1700837 to your computer and use it in GitHub Desktop.
InfoQ - Building REST with Spring - the Web/Controller layer
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 | |
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