【发布时间】:2025-12-18 02:00:02
【问题描述】:
如何使用 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 类中应用了约束的所有字段都在正确验证。
Java 类(如 String 和 Map)的方法参数不会发生验证。
我正在使用带有休眠验证器的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());
}
【问题讨论】:
-
是
profileIdrequestBody吗? -
是的 profileId 作为请求正文,它只是字符串而不是键值对
-
你能用javascript显示requestBody调用吗?
-
你好。您能否解释一下您对
@RequestBody @Valid String的期望?什么是验证?我认为你应该改用@RequestBody(required = true)。 -
Mickael, "public @interface RequestBody { boolean required() default true; }" 默认为 true
标签: java spring spring-boot bean-validation