Reputation: 115
In my app (springboot 2.+) I have a RestController like
@RestController
@RequestMapping("/")
public class DeviceController {
@GetMapping(value = "/devices") {
public ResponseEntity<String> devices() {
...
}
}
}
Now, request with URI: /devices - returns all devices
But request with URI: /devices?unknown_any_param=2 - also returns all devices
How can I make it so when I passing any unknown parameters, this method devices()
is not calling, i.e. is returning the error '400 Bad request'?
I was try to point annottion like @GetMapping(value = "/devices", params={}) , but it didn't help.
Upvotes: 0
Views: 297
Reputation: 21
I believe you should respond back with 404 'NOT FOUND' as there is no such device available with unknown_any_param=2.
Still if you want to check-
You can use Reflection API to check if key is valid or not. Consider-
public class DeviceDto{
private String knownValue;
@JsonProperty("unknown_any_param")
private String unknownValue;
}
case 1: If param is same as the variable name.
DeviceDto.class.getDeclaredField("knownValue");
case 2: If param is same as the value in @JsonProperty and you know the variable name
DeviceDto.class.getDeclaredField("unknownValue")
.getAnnotation(JsonProperty.class)
.value();
case 2: If param is same as the value in @JsonProperty and you don't know the variable name
Arrays.asList(DeviceDto.class.getDeclaredFields()).stream()
.filter(r -> "unknown_any_param"
.equals(r.getAnnotation(JsonProperty.class).value()))
.findFirst();
Upvotes: 0
Reputation: 137
You can fetch all the parameters passed as below
public ResponseEntity<String> devices(
@RequestParam Map<String,String> requestParameters)
Now check they keys if request parameter passes a valid list of parameters else
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
Upvotes: 1