Reputation: 323
I am new to Spring Boot and I have this problem.
and I still get 200 OK even though I don't provide "data"
Why do you think this is happening?
Any Help is appreciated.
Best
Upvotes: 1
Views: 12738
Reputation: 6963
You should use @RequestParam
as opposed to @PathParams
in this case.
But validation can also be applied to @PathParam
@GetMapping(path = "extra")
public String doExtraThing(@RequestParam("data") String data) {
return "Data is: " + data;
}
Using @NotNull
If you hit this api directly from browser
http://localhost:8080/demo/extra
You should get something in the console, because your default request parameter is mandatory.
2021-03-06 08:55:20.872 WARN 2936 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'data' is not present]
To make it optional use
@RequestParam(value = "data", required = false) String data
Now when you try to hit http://localhost:8080/demo/extra?data=, you should get
Data is:
Now, when you make it required = false
and add @NotNull
annotation from javax.validation.constraints
package and hit the api again you should get 503 internal server error.
javax.validation.ConstraintViolationException: doExtraThing.data: must not be null
Using @NotBlank:
You can achieve the same behavior using @NotBlank from javax.validation.constraints
@NotNull Validate that the object is not null.
@NotBlank check for character sequence's (e.g. string) trimmed length is not empty.
You would use @NotBlank on strings more here
Upvotes: 1
Reputation: 305
When you use @NotNull
you're preventing String data
to have a null value. But in postman when you're sending data with an empty value, you're actually sending it with an empty String ""
. To prevent both null
values and empty strings use @NotBlank
.
@RestController
@Validated
public class HelloController {
@GetMapping(value = "/path")
public String getData(@Valid @PathParam("data") @NotBlank String data) {
return data;
}
}
If you want to send data
as null
to check if @NotNull
works, just uncheck it from the postman params (Don't send it). It should raise an exception in your application that data
cannot be null.
Upvotes: 1