代码之家  ›  专栏  ›  技术社区  ›  Nitin Gangwar

未传递Spring引导PathVariable获取404 URL不存在

  •  0
  • Nitin Gangwar  · 技术社区  · 2 年前

    在Spring web应用程序中创建GET端点时,我有一个路径变量(注释为 @PathVariable )传递给我的API。

    如果我没有在路径上传递任何值,控制器将以HTTP 404状态进行响应。

    终点: http://localhost:8080/observability-核心/v1/系统/

    如果我传递一个值,它会按预期响应(例如 http://localhost:8080/observability-core/v1/systems/123 )

    如果请求中缺少路径变量,我想抛出HTTP400BadRequest来指示没有传递类似的内容。

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

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

    {
        "timestamp": "2024-01-04T06:48:18.584+00:00",
        "status": 404,
        "error": "Not Found",
        "path": "/observability-core/v1/systems/"
    }
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   Tamas Csizmadia    2 年前

    我提出的解决方案:

    • 指定带参数和不带参数的路径: @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);
        }
    }
    

    一个测试用例:

    @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"));
        }
    
    }
    
        2
  •  0
  •   Arslan aka    2 年前

    你可以按照这个方法来完成它。

    @RequestMapping(“/可观测性核心/v1/系统”) 公共类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);
    }