首页 > 解决方案 > 如何使用字符串参数向 Spring Boot 休息端点添加验证?

问题描述

如何使用 String 参数验证 Spring Boot Rest 端点,这是我的端点示例。

@ResponseBody
@RequestMapping(value = "/getProfile", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getProfile(@RequestBody @Valid @NotEmpty String profileId){}

甚至认为我添加@valid@NonEmpty约束它没有得到验证。

但它适用于其他课程。例如,

@ResponseBody
    @RequestMapping(value = "/saveProfiles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> saveProfiles(@RequestBody @Valid PersistProfilesRequest request){}

这里 PersistProfilesRequest 类中应用了约束的所有字段都在正确验证。

使用 String 和 Map 等 java 类的方法参数不会进行验证。

我正在使用spring boot 1.3.0休眠验证器。

如何使用字符串参数向休息端点添加验证?

编辑

我正在使用junit和mockmvc来测试端点,下面是测试用例

@Test
public void testGetProfile() throws Exception{

    String profileId = "   ";

    this.mockMvc.perform(post("/getProfile").content(profileId).accept(MediaType.APPLICATION_JSON).contentType("application/json"))
                .andDo(print())
                .andExpect(status().isInternalServerError());

}

标签: javaspringspring-bootbean-validation

解决方案


您可以尝试使用 @Validated 注释您的控制器类。就我而言,它有所帮助。

@Validated
@RestController
@RequestMapping(path = "/api/somethin")
public class LegacyRestController {

推荐阅读