我的问题是我需要实现rest api来搜索学生根据其属性 以下是我的网址。
http/my system/vo1/students/search?firstname=ABC&responseType=summary http/my system/vo1/students/search?age=ABC&responseType=summary http/my system/vo1/students/search?id=ABC& responseType =summary http/my system/vo1/students/search?mobile=ABC& responseType =summary http/my system/vo1/students/search?lastname=ABC& responseType =summary http/my system/vo1/students/search?education=ABC& responseType=summary http/my system/vo1/students/search?working=ABC& responseType =summary http/my system/vo1/students/search? responseType =summary
responseType可以是摘要,层次结构,也可以在功能中添加更多类型。
所以我有单个URI“/我的系统/ vo1 /学生/搜索?”具有不同的参数 并且用户将发送最多两个可选参数,min是必须的一个是responseType
在春天我们可以将具有不同请求参数的单个uri映射到不同的方法,如下所示
@RequestMapping(value = “my system/vo1/students/search", method = RequestMethod.GET)
@ResponseBody
public Students searchStudentByName(
@RequestParam(value = “name",required = true) String name,
@RequestParam(value = “ responseType", required = true) String responseType)
{
//do student fetching works
}
@RequestMapping(value = “my system/vo1/students/search", method = RequestMethod.GET)
@ResponseBody
public Students searchStudentByAge(
@RequestParam(value = “age",required = true) int age,
@RequestParam(value = “ responseType", required = true) String responseType)
{
//do student fetching works
}
依此类推..我们可以为此编写9种不同的方法。
另一种方法是只创建一种方法。
@RequestMapping(value = “my system/vo1/students/search", method = RequestMethod.GET)
@ResponseBody
public Students searchStudentByAge(
@RequestParam(value = “firstname",required = true) String age,
@RequestParam(value = “age",required = false) int age,
@RequestParam(value = “lastname",required = false) String lastname,
@RequestParam(value = “working",required = false) String working,
//add more for each field that will be present in url...........
@RequestParam(value = “ responseType", required = true) String responseType)
{
//do student fetching works
}
在第二种方法中,我们可以编写单独的验证器来验证输入请求。
我有以下问题
答案 0 :(得分:2)
一种方法就足以满足responseType的Pathvariable。您还可以将搜索参数移动到SearchCriteria类并执行JSR303
的验证@RequestMapping(value ="/search/{responseType}", method =RequestMethod.GET)
@ResponseBody
public Students searchStudent(@Pathvariable String responseType, @RequestBody @valid SearchCriteria criteria, BindingResult result)
{
if(result.hasErrors()){
// deal with your validation errors here
}
// Result= SearchService.search(criteria);
}
您的搜索条件将如下所示
Class SearchCriteria{
@NotEmpty
@Getter @Setter private String firstname;
@Min(1)
@Getter @Setter int age;
}
更多验证限制here
Spring MVC和JSR303示例here
答案 1 :(得分:1)
在这种情况下,你肯定应该使用一个RequestMapping(第二个选项)。如果您以后想要结合查询参数怎么办?组合爆炸!
确保您了解JPA Criteria API,或查看Jooq和QueryDSL。这会让你的生活更轻松。