@RequestParam 任意值

@RequestParam with any value

我的@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 请求:

GET:   /customers/
GET:   /customers?email=emai@email.com
GET:   /customers?phone=8-812-872-23-34

但如果有必要,可以为请求添加更多参数。如果它将是 10 或... 20 个参数,则上述方法的主体出现得离谱! 如果有任何方法可以将 @RequestParam 的值传递给方法体,我可以实现,例如:

@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?

您只需将 HttpServletRequest 添加为方法参数,Spring 就会将其提供给您:

@GetMapping
public List<User> getByParameterOrAll(@RequestParam(value = "email", required = false) 
String email,
                                      @RequestParam(value = "phone", required = false) 
String phone, HttpServletRequest request)

然后,你可以使用HttpServletRequestAPI获取传递的参数列表:

request.getParameterNames()request.getParameterMap()

在此处查看文档:

https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()

@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){ 
....
}

将以地图的形式为您提供所有参数和值。

您不能对请求中的不同名称-值使用单个@RequestParam。另一种方法可以检索请求的所有@RequestParam,如 this aswer