如何在REST API中实现过滤 [英] How to implement filtering in REST api

查看:177
本文介绍了如何在REST API中实现过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring mvc和spring jpa构建用于数据库连接的静态API. 我需要创建一个get api,该API可以基于filterString(作为查询参数传递给GET请求的结果)过滤结果.

I am building a restful api's using spring mvc and spring jpa for database connection. I have requirement to create a get api which can filter the results based on filterString(passed as query parameter to GET request).

用于过滤员工对象的GET api示例为

Example GET api for filter employee objects is

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

当前,我通过使用regX解析filterString并从中创建"spring jpa Specification"对象来实现此目标

Currently I am achieving this by parse the filterString using regX and create the "spring jpa Specification" object from it

下面是代码段

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服务器端实现过滤的最佳方法是什么?

I have seen many REST api's which support the filtering like this. Can anyone suggest what is the best way to implement filtering on RESt server side?

推荐答案

我使用 rsql-parser 在我的项目中.我解析创建条件对象或sql查询的查询字符串.

I use rsql-parser in my projects. I parse the query string creating the criteria object or the sql query.

这篇关于如何在REST API中实现过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆