簡體   English   中英

如何在REST API中實現過濾

[英]How to implement filtering in REST api

我正在使用spring mvc和spring jpa構建用於數據庫連接的靜態api。 我需要創建一個get api,該API可以基於filterString(作為查詢參數傳遞給GET請求的結果)過濾結果。

用於過濾員工對象的示例GET API是

http://localhost:8080/api/v1/employee?filter="(firstName eq john) and (lastName eq doe) or (empId eq 123)"

目前,我正在通過使用regX解析filterString並從中創建“ spring jpa Specification”對象來實現此目的

下面是代碼片段

public List<Employee> searchEmployee(String filter) throws Exception {
        // filter = "/"(firstName eq john) and (lastName eq doe) or (empId eq 123)/""
        // remove the " characters from start and end
        filter = filter.replaceAll("^\"|\"$", "");

        // spit the string basis of and/or
        String[] value = filter.split("(((?<=or)|(?=or)))|(((?<=and)|(?=and)))");
        Specification specs = null;
        String op = null;
        for (String f : value) {
            if (!"or".equalsIgnoreCase(f) && !"and".equalsIgnoreCase(f)) {
                String[] p = f.trim().split("\\s{1,}");
                if (p != null && p.length == 3) {
                    EmployeeSpecification es = new EmployeeSpecification(new SearchCriteria(p[0], p[1], p[2]));
                    if (specs == null ) {
                        specs = Specification.where(es);
                    } else {
                        if ("or".equalsIgnoreCase(op)) {
                            specs = specs.or(es);
                        } else if ("or".equalsIgnoreCase(op)) {
                            specs = specs.and(es);
                        }
                    }

                } else {
                    throw new Exception("Invalid search criteria");
                }

            } else {
                op = f;
            }


           List<Employee> l = empDao.findAll(specs);

          return l;

        }

我見過很多支持這種過濾的REST API。 誰能建議在RESt服務器端實現過濾的最佳方法是什么?

我在項目中使用rsql-parser 我解析創建條件對象或sql查詢的查詢字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM