2

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?

deFreitas
  • 4,196
  • 2
  • 33
  • 43
Jelly
  • 972
  • 1
  • 17
  • 40

3 Answers3

4

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

R.G
  • 6,436
  • 3
  • 19
  • 28
2

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

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()

mikeb
  • 10,578
  • 7
  • 62
  • 120
  • And does it make sense to retain email and phone -params? – Jelly Feb 19 '20 at 16:31
  • 1
    I don't know, it's not my project. My guess would be no since they are not required, but it does illustrate that you can have both. If it were me, I'd remove them. – mikeb Feb 19 '20 at 16:48