Spring Boot handling multiple parameters in a get request

♀尐吖头ヾ 提交于 2021-01-29 09:17:53

问题


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.


回答1:


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:




回答2:


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

E.g.

@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);
}


来源:https://stackoverflow.com/questions/60421302/spring-boot-handling-multiple-parameters-in-a-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!