gpt4 book ai didi

java - Spring Boot Rest Web服务在Get Request中获取多个参数

转载 作者:行者123 更新时间:2023-12-01 18:11:29 25 4
gpt4 key购买 nike

我正在创建 Spring Boot Web 服务,并且我有一个模型员工

public class Employee {
private String id;
private String name;
private String designation;
private int salary;
//Has Getters and Setters
}

我想创建一个 Get 请求,它将根据用户给出的参数获取和过滤员工列表。

例如,如果用户给出员工的姓名和员工的职位,则 get 方法应过滤这些结果。对于各种参数组合,它应该可以工作。

@Override
public List<Employee> getEmployees(Map<String, Object> parameters) {
if (parameters.size() == 0)
// code to return all employees;
List<Employee> selectedEmployees = new ArrayList<Employee>();
for(Employee currentEmployee: new ArrayList<Employee>(employee.values())) {
for(Map.Entry<String, Object> check: parameters.entrySet()) {
try {
if(check.getValue() instanceof Integer) {
int condition = (int) Employee.class.getMethod("get" + check.getKey()).invoke(currentEmployee);
if((int) check.getValue() == condition)
selectedEmployees.add(currentEmployee);
} else if (check.getValue() instanceof String) {
String condition = (String) Employee.class.getMethod("get" + check.getKey()).invoke(currentEmployee);
if (((String) check.getValue()).equals(condition))
selectedEmployees.add(currentEmployee);
}
} catch(Exception e){
e.printStackTrace();
}
}
}
return selectedEmployees;
}

为了避免出现多个 if else 情况,我根据上面的字符串和整数过滤列表。

我认为我在以下在 Controller 中发送请求的代码中犯了错误。

@RequestMapping(value={"/employees","/{id}/{name}/{designation}/{salary}"})
public List<Employee> getEmployeeByProperty(EmployeeRequestParameters requestParams){
//Map for storing parameters to filter the List
Map<String, Object> filterParams = new HashMap<>();
if(requestParams.getIdParam().isEmpty()) {
filterParams.put("id", Integer.parseInt(requestParams.getIdParam()));
}
if(!requestParams.getNameParam().isEmpty()) {
filterParams.put("name", requestParams.getNameParam());
}
if(!requestParams.getDesignationParam().isEmpty()) {
filterParams.put("designation", requestParams.getDesignationParam());
}
if(requestParams.getSalaryParam().isEmpty()) {
filterParams.put("salary", Integer.parseInt(requestParams.getSalaryParam()));
}
return EmployeeService.getEmployeesByProperty(filterParams);
}

最佳答案

如果 {id} 字段未满,则 {name} 或 {designation} 或 {salary} 为空。如果 {name} 或 {designation} 或 {salary} 为满,因为应该为 {id} 满。

@GetMapping("/employees")
public List<Employee> getEmployeeByProperty(@RequestParam(value = "id", required=false) String id,
@RequestParam(value = "name", required=false) String name,
@RequestParam(value = "designation", required=false) String designation,
@RequestParam(value = "salary", required=false) int salary) {
//Your codes
}

即使 {id} 为空,您也可以使用其他值。

关于java - Spring Boot Rest Web服务在Get Request中获取多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60462945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com