【问题标题】:Bean Validation and requested parameter in spring mvcspring mvc中的Bean验证和请求的参数
【发布时间】:2014-07-19 10:33:13
【问题描述】:

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

@Controller
public class test {

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

【问题讨论】:

    标签: java spring validation spring-mvc


    【解决方案1】:

    这样使用:

    public class Comment{
    
        @NotEmpty
        @Length(max = 140)
        private String text;
    
        //Methods are omitted.
    }
    

    现在在控制器中使用@Valid

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

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

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

    您还可以检查一下,了解一些替代方法: http://techblogs4u.blogspot.in/2012/09/method-parameter-validation-in-spring-3.html

    【讨论】:

    • @Valid 如何知道必须调用哪个验证器?
    • 谢谢! @Valid 注解是标准的 java-ee 注解还是完全是 spring?
    • 注意:@Valid 注解是标准 JSR-303 Bean Validation API 的一部分,不是 Spring 特定的构造。
    【解决方案2】:

    你可以试试这个

    @Controller
    public class test {
    
        @RequestMapping("/test.htm")
        public String test(@RequestParam(value="name",required=true) String name)
        {
            return "index";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多