[英]Spring Boot Rest Web Service fetching multiple parameters in Get Request
我正在創建 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} 為空,您也可以使用其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.