4

I'm using spring-data-rest.

Given following repository :

@RepositoryRestResource
public interface MyRepository extends PagingAndSortingRepository<MyEntity, Long> {}

The annotation @RestResource(exported = false) on the save() method makes the framework return a 405 Method Not Allowed error when using methods POST, PUT and PATCH.

My question : How can I just return a 405 error on PUT method while POST and PATCH are still allowed for this repository ?

Thanks !

pellenberger
  • 813
  • 1
  • 6
  • 7

2 Answers2

2

@SWiggels Thanks for your response :) Your solution didn't work for me... PUT is always allowed.

For others I found this one that worked :

@BasePathAwareController
public class MyEntityController {

    @RequestMapping(value = "/myentity/{id}", method = RequestMethod.PUT)
    public ResponseEntity<?> preventsPut() {
        return new ResponseEntity<>(HttpStatus.METHOD_NOT_ALLOWED);
    }
}
pellenberger
  • 813
  • 1
  • 6
  • 7
  • 1
    You indeed need to override the default behavior of the PUT handler. You should also add a custom handler for OPTIONS as shown by @SWiggels so as to improve the discoverability of your service. – Marc Tarin Apr 18 '16 at 09:32
0

You can add your allowed methods in the response of the options-probe.

@RequestMapping(method = RequestMethod.OPTIONS)
 ResponseEntity<Void> getProposalsOptions() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAllow(new HashSet<>(Arrays.asList(OPTIONS, PATCH, POST)));
    return new ResponseEntity<>(headers, HttpStatus.NO_CONTENT);
}

This allows only Options, Patch, Post as request-methods. For every other tried method you get a HTTP-405-Error.

SWiggels
  • 2,159
  • 1
  • 21
  • 35
  • Your solution assigns _OPTIONS, PATCH, POST_ to the _Allow_ header of the response, but it does not forbid other methods. – Marc Tarin Apr 18 '16 at 09:29