java Sping Boot PathVariable not passed获取404 URL不存在

1yjd4xko  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(107)

在Spring Web应用程序中创建GET端点时,我将路径变量(用@PathVariable注解)传递给我的API。
如果我没有在路径上传递任何值,控制器将返回HTTP 404状态。

*端点:http://localhost:8080/observability-core/v1/systems/

如果我传递一个值,它会按预期响应(例如http://localhost:8080/observability-core/v1/systems/123
如果请求中缺少路径变量,我想抛出HTTP 400 Bad Request来表示没有传递。

PS:- * 当我用上面的URL点击请求时,我没有得到任何日志,这意味着没有请求到达应用程序。这可能意味着端点不存在,这是误导。在这种情况下,我如何自定义错误响应?*

Spring控制器端点的默认响应:

{
    "timestamp": "2024-01-04T06:48:18.584+00:00",
    "status": 404,
    "error": "Not Found",
    "path": "/observability-core/v1/systems/"
}

字符串

vaqhlq81

vaqhlq811#

我建议的解决方案:

  • 指定带和不带参数的路径:@GetMapping(value = { "/path", "/path/{param}" })
  • 将Path变量标记为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 param is required");
        }
        return ResponseEntity.ok("The first param is: " + firstParam);
    }
}

字符串

A测试用例:

@SpringBootTest
@AutoConfigureMockMvc
class FooControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void whenParameterIsPassesShouldReturnOk() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo/param"))
                .andExpect(status().isOk())
                .andExpect(content().string("The first param is: param"));
    }

    @Test
    void whenParameterIsNotPassedShouldReturnBadRequest() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo/"))
                .andExpect(status().isBadRequest())
                .andExpect(content().string("The first param is required"));
    }

}

xjreopfe

xjreopfe2#

你可以通过遵循这种方法来完成它。
@RequestMapping(“/observability-core/v1/systems”)public class YourController {

@GetMapping("/{id}")
public ResponseEntity<String> getSystemDetails(@PathVariable(required = false) String id) {
    if (id == null) {
        // Handle the case where the path variable is not provided
        return new ResponseEntity<>("ID not provided in the request.", HttpStatus.BAD_REQUEST);
    }

    // Your existing logic when the ID is provided
    return new ResponseEntity<>("System details for ID: " + id, HttpStatus.OK);
}

字符串

相关问题