@RequestParam具有任何值 [英] @RequestParam with any value
问题描述
我的@Restcontroller中有以下方法:
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;
}
此方法允许处理以下GET请求:
This method allows to handle following GET-requests:
GET: /customers/
GET: /customers?email=emai@email.com
GET: /customers?phone=8-812-872-23-34
但是,如果需要,可以添加更多参数以供请求.如果是10或... 20个参数,上述方法的主体就大肆宣传了! 如果有任何方法可以将@RequestParam的值传递给方法主体,例如,我可以实现:
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 .....
}
有什么方法可以在method-body中使用@ RequestParam-value吗?
Is there any way to use @RequestParam-value in method-body?
推荐答案
您只需添加HttpServletRequest
作为方法参数,Spring就会将其提供给您:
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)
然后,您可以使用HttpServletRequest API获取传递的参数列表:
Then, you can use the HttpServletRequest API to get the list of parameters passed:
request.getParameterNames()
或request.getParameterMap()
在此处查看文档:
https://docs.oracle .com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()
这篇关于@RequestParam具有任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!