我正在创建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的情况,我正在根据上面的String和Integer过滤列表。
我想我在控制器中发送请求的下面的代码中犯了一个错误。
@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}为空,您也可以使用其他id。