简体   繁体   English

在Spring 3 MVC中验证@RequestParam

[英]Validating @RequestParam in Spring 3 MVC

How do I validate Spring @RequestParam so that they are in BindingResult with out having to use some sort of POJO transfer object (@ModelAttribute)? 如何验证Spring @RequestParam以便它们在BindingResult中而不必使用某种POJO传输对象(@ModelAttribute)?

I could use MapBindingResult and put the request parameters in that but then I have to get that binding result into the model. 我可以使用MapBindingResult并将请求参数放入其中,但我必须将该绑定结果放入模型中。

Which I can do with org.springframework.validation.BindingResult.MODEL_KEY_PREFIX + name. 我可以使用org.springframework.validation.BindingResult.MODEL_KEY_PREFIX +名称。

Is there a better way to bind and validate request parameters (instead of making another POJO)? 有没有更好的方法来绑定和验证请求参数(而不是制作另一个POJO)?

If you are using Spring MVC 3.0 or later, you can use the declarative validation support Spring provides. 如果您使用的是Spring MVC 3.0或更高版本,则可以使用Spring提供的声明性验证支持 You would then declare the validation restrictions on the model bean and add the @Valid annotation to your form backing bean as described in the chapter "Spring Validation" in the reference docs. 然后,您将在模型bean上声明验证限制,并将@Valid注释添加到表单支持bean,如参考文档中的“Spring Validation”一章所述。

If you add a BindingResult parameter directly after the bean being validated, you can then check for validation errors in your controller: 如果在验证bean之后直接添加BindingResult参数,则可以检查控制器中的验证错误:

// .. in the bean class
public class MyBean {
    @NotNull
    private String name;
    // ..
}

// .. in the @Controller
public ModelAndView doSomething(@Valid MyBean data, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) { 
        // back to form
    }
    // do something with the bean
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM