如果缺少特定的查询参数,我如何简单地重定向 url?
@RestController
public class PersonController {
//only in case the "sort" query parameter is missing
@GetMapping("/persons")
public String unsorted() {
return "redirect:/persons?sort=name";
}
//only in case the "sort" query parameter exists
@GetMapping("/persons")
public String sorted() {
//...
}
}
最佳答案
- 使用@RequestParam提取查询参数
- 为@RequestParam 添加参数:value、defaultValue、required
使用 java >= 8:
@RestController
public class PersonController {
@GetMapping("/persons")
public String personList(@RequestParam(value = "sort", defaultValue = "name") Optional<String> sort) {
//handling process here
}
}
使用 java < 8:
@RestController
public class PersonController {
@GetMapping("/persons")
public String personList(@RequestParam(value = "sort", defaultValue = "name", required=false) String sort) {
//handling process here
}
}
关于java - 如何添加多个查询参数不同的 RestController 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57958864/