问题
I have the following metod in my @Restcontroller:
@GetMapping
public List<User> getByParameterOrAll(
@RequestParam(value = "email", required = false) String email,
@RequestParam(value = "phone", required = false) String phone) {
List<User> userList;
if ((email != null && !email.isEmpty()) && (phone == null || phone.isEmpty())) {
userList = super.getByEmail(email);
} else if ((email == null || email.isEmpty()) && (phone != null)) {
userList = super.getByPhone(phone);
} else {
userList = super.getAll();
}
return userList;
}
This method allows to handle following GET-requests:
GET: /customers/
GET: /customers?email=emai@email.com
GET: /customers?phone=8-812-872-23-34
But if necessary to add some more parameters for request. If it will be 10 or... 20 params,body of above method arrise outrageously! If there any way to pass value of @RequestParam to the method-body, I could realize, for example:
@GetMapping
public List<User> getByParameterOrAll(
@RequestParam(value = "any", required = false) String any) {
if (value=="email") {
userList = super.getByEmail(email);
} else if (value=="email") {
userList = super.getByPhone(email);
} else if .....
}
Is there any way to use @RequestParam-value in method-body?
回答1:
You can just add HttpServletRequest
as a method parameter and Spring will give it to you:
@GetMapping
public List<User> getByParameterOrAll(@RequestParam(value = "email", required = false)
String email,
@RequestParam(value = "phone", required = false)
String phone, HttpServletRequest request)
Then, you can use the HttpServletRequest API to get the list of parameters passed:
request.getParameterNames()
or request.getParameterMap()
See the docs here:
https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()
回答2:
@RequestParam
When an @RequestParam annotation is declared as a Map or MultiValueMap, without a parameter name specified in the annotation, then the map is populated with the request parameter values for each given parameter name.
@GetMapping
public List<User> getByParameterOrAll(@RequestParam Map<String, String> parameters){
....
}
will get you all the parameters and values as a map.
回答3:
You can't use single @RequestParam for different name-value on the request. Another way for you can be retrieve all @RequestParam of the request like this aswer
来源:https://stackoverflow.com/questions/60304684/requestparam-with-any-value