java - Spring - 永远不会调用@Valid 验证

标签 java spring validation

尝试简单地验证我的 bean 的一个字段而不是手动执行它想检查 Spring Validation,但到目前为止运气不佳。

简而言之:

当我调用 @RestController 的方法时,似乎永远不会调用带有 @Valid 注释的验证

我的代码:

pom.xml(验证部分)

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

Spring是4.1.1版本

validator

package mypackage;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public class UtenteValidator implements Validator{

    public UtenteValidator() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return UtenteLite.class.equals(clazz);
    }

//validation test
    @Override
    public void validate(Object target, Errors errors) {
        UtenteLite user = (UtenteLite) target;

          if(user.getName != "foo") {
              errors.rejectValue("name", "name not correct");
          }

    }




}

Controller

package myPackage;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/users")
public class UsersController {


    public UsersController() {

    }

//tried to put @InitBinder, but no luck
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UtenteValidator());
    }

    @ResponseBody
    @RequestMapping(value="", method=RequestMethod.PUT)
    public <T> ResponseEntity<T> aggiornaUtente(@RequestBody @Valid UtenteLite utente, BindingResult result)
    {
        ResponseEntity<T> responseEntity=null;

        return responseEntity;
    }


}

Te BindingResult 结果对象始终显示零错误,并且永远不会调用 validatesupportsinitBinder 方法.

找到这个 tutorial上面写着:

When @InitBinder methods get called?

The @InitBinder annotated methods will get called on each HTTP request if we don't specify the 'value' element of this annotation.

WebDataBinder argument is specific to a model attribute. That means each time a model attribute is created by Spring this method will get called with a new instance of WebDataBinder.

所以我尝试将我的 Controller 方法更改为此添加一个 @ModelAttribute 现在验证代码被调用但是 requestBody 对象(“utente”对象)是空的,所以验证总是失败,因为字段都是空值:

@ResponseBody
    @RequestMapping(value="", method=RequestMethod.PUT)
    public <T> ResponseEntity<T> aggiornaUtente(@RequestBody @Valid @ModelAttribute("utente") UtenteLite utente, BindingResult result)
    { 
...
}

utente 方法参数以 JSON 作为请求正文传递。

最佳答案

好的,

经过几次尝试,我成功地生成了一个可行的解决方案只需在我的 pom.xml 中添加 hibernate-validation 工件引用

我错误地认为仅当我在 bean 属性上使用验证注释(如 @NotNull、@Pattern 等)时,hibernate-validator 才是强制性的。

所以只有通过添加这个片段我才能解决我的问题(希望这会为其他人节省几个小时的工作):

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>

现在完整的代码是:

验证者

package mypackage;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public class UtenteValidator implements Validator{

    public UtenteValidator() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return UtenteLite.class.equals(clazz);
    }

//validation test
    @Override
    public void validate(Object target, Errors errors) {
        UtenteLite user = (UtenteLite) target;

          if(user.getName != "foo") {
              errors.rejectValue("name", "name not correct");
          }

    }




}

Controller

package myPackage;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/users")
public class UsersController {


    public UsersController() {

    }

//tried to put @InitBinder, but no luck
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UtenteValidator());
    }

    @ResponseBody
    @RequestMapping(value="", method=RequestMethod.PUT)
    public <T> ResponseEntity<T> aggiornaUtente(@RequestBody @Valid UtenteLite utente)
    {
        ResponseEntity<T> responseEntity=null;

        return responseEntity;
    }


}

关于java - Spring - 永远不会调用@Valid 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922860/

相关文章:

java - 回滚 RuntimeException : org. springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback;错误的 SQL 语法 [ - Spring Batch 问题

c# - 创建返回多条错误消息的自定义 ValidationAttribute 类

java - Hibernate JSR303 验证和错误生成的 propertyPath

java - Android 应用程序 - onCreateView 中的 HttpURLConnection

java - 对此 Java 示例中的 "super"关键字感到困惑

java - 当 RequestBody 参数的某些属性为 null 时,如何返回 400 HTTP 错误代码?

grails - 用户输入验证-Grails验证

java - 如何使用索引循环根据位置替换字符

java - iCal 中的 HTML 使用 iCal4j

spring - 如何在使用响应式(Reactive)数据源的 WebFlux 上编写自定义验证器