【问题标题】:how can i add validation to a spring boot rest endpoint with a string parameter?如何使用字符串参数向 Spring Boot 休息端点添加验证?
【发布时间】: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());

}

【问题讨论】:

  • profileId requestBody 吗?
  • 是的 profileId 作为请求正文,它只是字符串而不是键值对
  • 你能用javascript显示requestBody调用吗?
  • 你好。您能否解释一下您对 @RequestBody @Valid String 的期望?什么是验证?我认为你应该改用@RequestBody(required = true)
  • Mickael, "public @interface RequestBody { boolean required() default true; }" 默认为 true

标签: java spring spring-boot bean-validation


【解决方案1】:

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

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

【讨论】:

  • 是java验证框架和hibernate Validator只对bean有效吗?
  • 不,实际上不是。验证注解及其验证器主要用于基本类型。 @NotEmpty 可用于字符串和集合。在您的情况下,有一些不同的原因无法验证这些参数。如果我为此做一些额外的配置,明天我可以再次查看我自己的项目。
  • 哦,我看到了问题,尝试将您的方法更改为 GET(而不是 Post)并将替换 '@RequestBody' 更改为 '@RequestParam'。
  • 这里是控制器类中的注解,--- Validated RestController RequestMapping("/kvassist") ComponentScan(basePackages = { "com.app.profile" })
  • 更新了端点声明 -- ResponseBody RequestMapping(value = "/getProfile", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE, consumes=MediaType.TEXT_PLAIN_VALUE) public ResponseEntity getProfile( @RequestParam(name="p") 有效的电子邮件字符串 profileId)