我提出的解决方案:
- 同时指定带有和不带参数的路径:
@GetMapping(value = { "/path", "/path/{param}" })
- 将路径变量标记为
required = false
(@PathVariable(required = false) String param
)
- 处理缺少参数的情况,并按需求响应(在你的案例中,返回HTTP状态码400)
最小化示例:
@RestController
@RequestMapping("/foo")
public class FooController {
@GetMapping(value = { "/{firstParam}", "/" })
public ResponseEntity<String> getFoo(@PathVariable(required = false) String firstParam) {
if (null == firstParam) {
return ResponseEntity.badRequest().body("The first parameter is required");
}
return ResponseEntity.ok("The first parameter is: " + firstParam);
}
}
测试用例:
@SpringBootTest
@AutoConfigureMockMvc
class FooControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void whenParameterIsPassedShouldReturnOk() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/foo/param"))
.andExpect(status().isOk())
.andExpect(content().string("The first parameter is: param"));
}
@Test
void whenParameterIsNotPassedShouldReturnBadRequest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/foo/"))
.andExpect(status().isBadRequest())
.andExpect(content().string("The first parameter is required"));
}
}