We have to use ResponseEntity or use @ResponseStatus to give the correct status code. But this could be linked to the type of the HTTP METHOD (GET, POST ..) so that we would not need to put more code.
The @ResponseStatus annotation is part of Spring Framework. I'll transfer your issue for them to consider. I suspect that they may not want to add an additional attribute on @ResponseStatus given that it will then provide a third way of setting the status code.
But this could be linked to the type of the request (GET, POST ..) so that we would not need to put more code.
What do you mean by "linked" in the above sentence?
In other words, what are you explicitly proposing?
If I put @PostMapping automatically when making the POST request, the status code returned will be 201 CREATED, because the default for all Mapping is to return the status code 200 OK.
Ex: repository.save(entity); By default this would return status code 200 and not 201.
OK. So you are proposing that Spring infer a default status code based on the mapped HTTP method.
Yes exactly that. Sorry for my explanation, I am learning to speak English.
Please note that this is actually a _duplicate_ of #18578 which got bulk closed.
See also the discussion in https://github.com/sbrannen/spring-composed/issues/10.
I think the key is this has to be done selectively (e.g. @RestController but not necessarily any @Controller) and at this point in time, it probably has to be explicit, e.g. via configuration or a protected method somewhere. Either of those doesn't seem ideal, one would just add more configuration, and the other would require deciding where to apply which status.
One thought is that it's easy to create a custom annotation that combines HTTP POST with 201:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = {RequestMethod.POST})
@ResponseStatus(HttpStatus.CREATED)
public @interface POST {
@AliasFor(annotation = RequestMapping.class)
String[] value() default {};
}
@RestController
public class AccountController {
@POST("/accounts")
Account handle(@RequestBody Account account) {
return ... ;
}
The advantage of this is that it's flexible enough to apply where needed without being any more verbose.
If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.
For me, the ideal is that Spring inferred the status code of the post for example, if it is not possible, fine.