Jelly
Jelly

Reputation: 1298

@RequestParam with any value

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:   /[email protected]
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?

Upvotes: 2

Views: 1084

Answers (3)

Salvatore Rinaudo
Salvatore Rinaudo

Reputation: 276

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

Upvotes: 2

R.G
R.G

Reputation: 7131

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

Upvotes: 4

mikeb
mikeb

Reputation: 11267

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

Upvotes: 1

Related Questions