简体   繁体   中英

Spring Boot handling multiple parameters in a get request

I am new to using Spring boot framework. I want to create a @GetMapping where based on what user enters in the parameter either Property1 Name(String) or Protery2 Designation(String) or Property3 Salary(Integer) the method should be able to get the List of employees based on one or more properties. I can create individual methods but I do not want to do that. I want to do something like this:

@GetMapping("/employee")
public List<Employee> getEmployee(Params parameters)
{
    // Filter the list based on parameters provided and return the list
}

Also, I am not understanding how to handle parameters for example, if it is an integer there is only one column but if the user enters string there are two columns. If the user does not specify the parameter name I have to handle that.

You can use @RequestParam Map<String, String> params to bind all parameters to one variable

Eg

@RequestMapping(value="/params", method = RequestMethod.GET)
public ResponseEntity getParams(@RequestParam Map<String, String> params ) {

   System.out.println(params.keySet());
   System.out.println(params.values());

   return new ResponseEntity<String>("ok", HttpStatus.OK);
}

You can define the three parameters using the @RequestParam annotation and check which one is non-empty:

@GetMapping("/employee")
public List<Employee> getEmployee(@RequestParam(defaultValue = "empty") String name, @RequestParam(defaultValue = "empty") String designation, ....
{
    // check which one is not empty and perform logic
    if (!name.equals("empty")) {
      // do something 
  }
}

Regarding which parameter the user chooses: you can make a drop-down menu or a simple-radio selection, where the user chooses the search criteria himself (and where each criterion is mapped by a request parameter). For example:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM