gpt4 book ai didi

java - spring mvc 中的 Bean 验证和请求参数

转载 作者:行者123 更新时间:2023-12-02 05:37:29 25 4
gpt4 key购买 nike

是否可以以任何方式使用 validator 来验证 javax.validation.constraints 包中的请求参数? IE。像下面这样:

@Controller
public class test {

@RequestMapping("/test.htm")
public String test(@RequestParam("name") @NotNull String name)
{
return "index";
}
}

最佳答案

使用这种方式:

public class Comment{

@NotEmpty
@Length(max = 140)
private String text;

//Methods are omitted.
}

现在在 Controller 中使用@Valid

 @Controller
public class CommentController {

@RequestMapping(value = "/api/comment", method = RequestMethod.POST)
@ResponseBody
public Comment add(@Valid @RequestBody Comment comment) {
return comment;
}
}

当您在 Controller 中为 Comment 对象应用 @Valid 时,它将应用 Comment 类及其属性中提到的验证,如

@NotEmpty
@Length(max = 140)
private String text;

您还可以查看以下替代方法: http://techblogs4u.blogspot.in/2012/09/method-parameter-validation-in-spring-3.html

关于java - spring mvc 中的 Bean 验证和请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24839394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com