Spring 用于过滤资源的休息控制器

Spring rest controller to filter a resource

在我的 spring 启动应用程序中,我有一个问题作为资源,包含以下字段。

    [  
       {  
          "questionId":6,
          "area":"TECHNICAL",
          "title":"Find the index of first 1 in an infinite sorted array of 0s and 1s",
          "description":"Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first 1 in that array. As the array is infinite, therefore it is guaranteed that number 1 will be present in the array.",
          "state":"ACTIVE",
          "difficultyLevel":"EASY",
          "skills":[  
             {  
                "skillId":1,
                "skillName":"ALGORITHM"
             },
             {  
                "skillId":2,
                "skillName":"PROGRAMMING"
             }
          ],
          "proposedBy":"agrawalo",
          "noOfTimesUsed":0,
          "examples":null,
          "probes":null,
          "approvedBy":null,
          "addedBy":null,
          "dateCreated":"2018-05-16T19:29:11.113",
          "dateLastUpdated":"2018-05-16T19:29:11.113"
       }, 
       {
        ...
       },
       ...
    ]

我想写控制器来过滤问题。

例如:

1./questions?area="technical"。 returns 询问区域为 "technical" 的控制器。为此,我编写了以下方法。

@RestController
public class QuestionController { 
    @RequestMapping("/questions",  method = GET)
    String getFilteredQuestions(@RequestParam("area") String questionArea) {

    }
}

2./questions?area="technical"&skill="programming"。现在,我想写一个 returns 问题的控制器,面积为 "technical",技能为 "programming"。

实现此目的的一种方法是向 "getFilteredQuestion" 方法添加一个请求参数。

但是我最终会编写一个非常混乱的代码(比如我想添加更多过滤器)来检查哪些请求参数为空,哪些不是,并基于应用过滤器。

@RestController
public class QuestionController {
    @RequestMapping("/questions",  method = GET)
    String getFilteredQuestions(@RequestParam("area") String questionArea, @RequestParam("skill") String questionSkill) {

    }
}

3./questions?skill="algorithm"&proposedby="agrawalo" ...

有什么干净的方法可以编写这样的控制器?

使用您支持的所有查询和过滤器参数创建一个 Java POJO。确保您可以将该 POJO 映射到 JSON,反之亦然。您的客户可以编辑 JSON 版本并将其与请求一起发送。您将它映射回您的 POJO,并将其传递给负责准备适当查询的业务逻辑。这样,您就可以保持控制器的方法不变。

也许你可以将问题 class 写成一个实体 class。

public class Question {
         private String title;
         private String description;
         private List<String> skills;
         private Date createdAt;

         public void setTitle(String title) {
             this.title = title;
         }
         public String getTitle() {
             return this.title;
         }

    }

然后通过这种方式你可以得到你的数据

@RestController
public class QuestionController {
    @RequestMapping("/questions",  method = GET)
    String getFilteredQuestions@RequestBody Question question) {

    }
}