java Spring 4 MVC 验证不起作用 - BindingResult hasErrors 为 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26993364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:01:27  来源:igfitidea点击:

Spring 4 MVC Validation not working - BindingResult hasErrors is false

javaspringspring-mvcspring-validator

提问by PDStat

I am unit testing a Spring controllers post method (using org.springframework.test.web.servlet.MockMvc), and I'm trying to confirm that when there are validation errors in the form it will send the view back to the form by checking the BindingResult.hasErrorsmethod.

我正在对 Spring 控制器 post 方法进行单元测试(使用org.springframework.test.web.servlet.MockMvc),并且我试图确认当表单中存在验证错误时,它会通过检查BindingResult.hasErrors方法将视图发送回表单。

Here is my test

这是我的测试

  @Test
  public void testFilterChannelProgrammesWhenChannelListAndGenreListAreEmptyAndProgNameIsTooLong() throws Exception {
    String progName = TestUtil.createStringWithLength(301);

    mockMvc.perform(post("/api/filter")
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .param("progName", progName)
        .sessionAttr("filter", new ProgrammeSearchDTO())
        )
        .andExpect(status().isOk())
        .andExpect(view().name("api/filter"))
        .andExpect(forwardedUrl("/WEB-INF/jsp/api/filter.jsp"))
        .andExpect(model().attributeHasFieldErrors("filter", "progName"))
        .andExpect(model().attributeHasFieldErrors("filter", "genreIdList"))
        .andExpect(model().attributeHasFieldErrors("filter", "channelIdList"))        
        .andExpect(model().attribute("filter", hasProperty("progName", is(progName))));

    verifyZeroInteractions(channelProgrammeServiceMock);
  }

Here is the DTO that the session attribute is bound to

这里是 session 属性绑定的 DTO

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

public class ProgrammeSearchDTO {

  @NotEmpty
  private String[] channelIdList;

  @NotEmpty
  private String[] genreIdList;

  private String fromDateTime;
  private String toDateTime;

  @Length(max = 200)
  private String progName;

  private boolean subtitled;
  private boolean signed;
  private boolean film;

  public String[] getChannelIdList() {
    return channelIdList;
  }

  public String getFromDateTime() {
    return fromDateTime;
  }

  public String[] getGenreIdList() {
    return genreIdList;
  }  

  public String getProgName() {
    return progName;
  }

  public String getToDateTime() {
    return toDateTime;
  }

  public boolean isFilm() {
    return film;
  }

  public boolean isSigned() {
    return signed;
  }

  public boolean isSubtitled() {
    return subtitled;
  }

  public void setChannelIdList(String[] channelIdList) {
    this.channelIdList = channelIdList;
  }

  public void setFilm(boolean film) {
    this.film = film;
  }

  public void setFromDateTime(String fromDateTime) {
    this.fromDateTime = fromDateTime;
  }

  public void setGenreIdList(String[] genreIdList) {
    this.genreIdList = genreIdList;
  }

  public void setProgName(String progName) {
    this.progName = progName;
  }

  public void setSigned(boolean signed) {
    this.signed = signed;
  }

  public void setSubtitled(boolean subtitled) {
    this.subtitled = subtitled;
  }

  public void setToDateTime(String toDateTime) {
    this.toDateTime = toDateTime;
  }  


}

And the controller method

和控制器方法

  @RequestMapping(value = "/api/filter", method = RequestMethod.POST)
  public String filterChannelProgrammes(@Valid @ModelAttribute ProgrammeSearchDTO programmeSearchDTO, BindingResult result, Model model) {
    if(result.hasErrors()) {
      return "api/filter";
    }
    model.addAttribute("results", null);
    return "redirect:filterResults";
  }

For this test the return "api/filter";should be actioned, but hasErrors()is always false. I have also tried with the following

对于此测试,return "api/filter";应采取行动,但hasErrors()始终为假。我也试过以下

  @RequestMapping(value = "/api/filter", method = RequestMethod.POST)
  public String filterChannelProgrammes(@Valid @ModelAttribute("filter") ProgrammeSearchDTO programmeSearchDTO, BindingResult result, Model model) {
    if(result.hasErrors()) {
      return "api/filter";
    }
    model.addAttribute("results", null);
    return "redirect:filterResults";
  }

But hasErrors()is still false

hasErrors()还是假的

EDIT

编辑

After some more digging I have this sorted, it also required the following in the context config xml

经过更多的挖掘,我对这个进行了排序,它还需要上下文配置 xml 中的以下内容

<mvc:annotation-driven />

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

And these dependencies in the maven pom.xml

而maven pom.xml中的这些依赖

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.2.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>javax.el-api</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>javax.el</artifactId>
        <version>2.2.4</version>
    </dependency>

采纳答案by PDStat

After some more digging I have this sorted, it also required the following in the context config xml

经过更多的挖掘,我对这个进行了排序,它还需要上下文配置 xml 中的以下内容

<mvc:annotation-driven />

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

And these dependencies in the maven pom.xml

而maven pom.xml中的这些依赖

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.2.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>javax.el-api</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>javax.el</artifactId>
        <version>2.2.4</version>
    </dependency>