Spring MVC 中的验证

发布于 2024-10-30 21:48:41 字数 44 浏览 1 评论 0原文

如何在验证器类中获取请求对象,因为我需要验证内容,即请求对象中存在的参数。

how to get the request object in the validator class, as i need to validate the contents ie the parameters present in the request object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迷鸟归林 2024-11-06 21:48:41

您有两种选择:

  • JSR 303(Bean 验证)验证器
  • Spring 验证器

对于 JSR 303,您需要 Spring 3.0,并且必须使用 JSR 303 注解来注解您的 Model 类,并在参数前面写入 @Valid Web 控制器处理程序方法。 (就像威利·惠勒在他的回答中展示)。另外,您必须在配置中启用此功能:

<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>

对于 Spring 验证器,您需要编写验证器(请参阅Jigar Joshi 的答案)实现了 org.springframework.validation.Validator 接口。您必须在控制器中注册您的验证器。在 Spring 3.0 中,您可以使用 WebDataBinder.setValidator (setValidator 它是一种方法超类 DataBinder

Example (from the spring docu)
@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new FooValidator());
    }

    @RequestMapping("/foo", method=RequestMethod.POST)
    public void processFoo(@Valid Foo foo) { ... }
}

有关更多详细信息,请参阅 Spring 参考,章节 5.7.4 Spring MVC 3 验证

顺便说一句:在 Spring 2 中,SimpleFormController 中有类似 setValidator 属性的东西。

You have two choices:

  • JSR 303 (Bean Validation) Validators
  • Spring Validators

For JSR 303 you need Spring 3.0 and must annotate your Model class with JSR 303 Annotations, and write an @Valid in front of you parameter in the Web Controller Handler Method. (like Willie Wheeler show in his answer). Additionaly you must enable this functionality in the configuration:

<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>

For Spring Validators, you need to write your Validator (see Jigar Joshi's answer) that implements the org.springframework.validation.Validator Interface. The you must register your Validator in the Controller. In Spring 3.0 you can do this in a @InitBinder annotated Method, by using WebDataBinder.setValidator (setValidator it is a method of the super class DataBinder)

Example (from the spring docu)
@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new FooValidator());
    }

    @RequestMapping("/foo", method=RequestMethod.POST)
    public void processFoo(@Valid Foo foo) { ... }
}

For more details, have a look at the Spring reference, Chapter 5.7.4 Spring MVC 3 Validation.

BTW: in Spring 2 there was someting like a setValidator property in the SimpleFormController.

岁月静好 2024-11-06 21:48:41

使用简单验证器(您的自定义验证器)
您不需要请求对象来获取验证器中的参数。你可以直接从.

例如:这将检查请求中名称为 nameage 的字段

public class PersonValidator implements Validator {

    /**
    * This Validator validates just Person instances
    */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

另请参阅

Using simple validator (your custom validator)
You don't need request object to get param there in Validator. You can directly have it from.

For example : This will check field from request with name name and age

public class PersonValidator implements Validator {

    /**
    * This Validator validates just Person instances
    */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

Also See

时光沙漏 2024-11-06 21:48:41

不是 100% 确定我正确地理解了你的问题,但是使用 Spring MVC,你将对象传递到方法中并对其进行注释(至少在 Spring 3 中),如下所示:

@RequestMethod(value = "/accounts/new", method = RequestMethod.POST)
public String postAccount(@ModelAttribute @Valid Account account, BindingResult result) {
    if (result.hasErrors()) {
        return "accounts/accountForm";
    }

    accountDao.save(account);
}

这里的相关注释是 @Valid,它是JSR-303。还包括 BindingResult 参数,以便您可以检查错误,如上所示。

Not 100% sure I'm following your question correctly, but with Spring MVC, you pass the object into the method and annotate it (at least with Spring 3), like so:

@RequestMethod(value = "/accounts/new", method = RequestMethod.POST)
public String postAccount(@ModelAttribute @Valid Account account, BindingResult result) {
    if (result.hasErrors()) {
        return "accounts/accountForm";
    }

    accountDao.save(account);
}

The relevant annotation here is @Valid, which is part of JSR-303. Include the BindingResult param as well so you have a way to check for errors, as illustrated above.

独享拥抱 2024-11-06 21:48:41

您可以轻松地使用 HttpServletRequest 参数添加另一个方法。

 public void validateReq(Object target, Errors errors,HttpServletRequest request) {

       // do your validation here
}

请注意,您并没有重写此处的方法

You could easily add another method with HttpServletRequest parameter.

 public void validateReq(Object target, Errors errors,HttpServletRequest request) {

       // do your validation here
}

Note that you are not overriding a method here

握住我的手 2024-11-06 21:48:41

当我使用 spring validator 验证验证码时,我也遇到同样的问题。
在验证器实现器中,我想从 HttpSession 获取正确的验证码(从 HttpServletRequest 获取 HttpSession)。

没有找到任何好的代码可以在验证器中获取它,太糟糕了!

有一些折衷方案如下:

  1. 在绑定表单 DTO 中添加一个附加字段(调用: CorrectCaptcha),在 Controller 方法中设置 HttpSession 中的字段值,然后您可以在验证器中进行验证

    public class UserRegisterDto {
        私有字符串正确验证码;
        //获取器、设置器
    }
    
  2. 在绑定形成DTO,然后可以在验证器中使用它。

    public class UserRegisterDto {
        私有 HttpServletRequest 请求;
        //获取器,设置器
    }
    
    @RequestMapping(value = "register.hb", method = RequestMethod.POST)
    公共字符串submitRegister(@ModelAttribute(“formDto”)@Valid UserRegisterDto formDto,HttpServletRequest请求,BindingResult结果){
        formDto.setRequest(请求);
        if (结果.hasErrors()) {
            返回“用户注册”;
        }
    }
    

I also have the same issue when i use spring validator validate captcha.
In the validator implementor, i want to get the correct-captcha from HttpSession(from HttpServletRequest get HttpSession).

Not found any good codes for get it in validator, so bad!!!

There are some compromise proposal as follow:

  1. In the binding form DTO add an additional field (call: correctCaptcha), in the Controller method set the field value from HttpSession , then you can validate in the validator

    public class UserRegisterDto {
        private String correctCaptcha;
        //getter,setter
    }
    
  2. Add the HttpServletRequest reference in the binding form DTO, then can use it in the validator.

    public class UserRegisterDto {
        private HttpServletRequest request;
        //getter ,setter
    }
    
    @RequestMapping(value = "register.hb", method = RequestMethod.POST)
    public String submitRegister(@ModelAttribute("formDto") @Valid UserRegisterDto formDto, HttpServletRequest request,BindingResult result) {
        formDto.setRequest(request);
        if (result.hasErrors()) {
            return "user_register";
        }
    }
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文