java - Spring setDisallowedFields 不起作用

标签 java validation spring-mvc testing spring-mvc-test

注册 Controller 不允许通过以下方式发送帐户 ID 字段:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.setDisallowedFields("id");
    binder.setRequiredFields("username","password","emailAddress");
} 

@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public String handleRegistration(@ModelAttribute Account account, BindingResult result) {
    if (result.hasErrors()) {
        return "customer/register";
    }

我运行以下测试以确保 ID 不被允许:

@Test
public void testPutRequestWithIdPassedRegistrationController() throws Exception {
    this.mockMvc.perform(post("/customer/register")
            .param("id", "1")
            .param("username", "shouldBeIgnored")
            .param("password", "123")
            .param("emailAddress", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="add9c8ded9e4cac3c2dfc8c9edcac0ccc4c183cec2c0" rel="noreferrer noopener nofollow">[email protected]</a>")
            .param("address.country", "RU")
            .param("address.city", "Nsk")
            .param("address.street", "Lenin"))
            .andExpect(model().hasErrors())
            .andExpect(view().name("customer/register"));
}

但是测试失败原因: java.lang.AssertionError:预期的绑定(bind)/验证错误

为了进行比较,这里的测试尝试在不传递不可为空字段的情况下创建帐户,并且通过良好,这意味着 setRequiredFields 工作正常:

@Test
public void testPutRequestWithoutNeededFieldsRegistrationController() throws Exception {
    this.mockMvc.perform(post("/customer/register"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(view().name("customer/register"))
            .andExpect(model().hasErrors())
            .andExpect(model().errorCount(3));
}

为什么会这样呢?如何确定该 id 不被允许?

最佳答案

Spring 不会将不允许的字段视为错误。 它只是将它们存储为 BindException 中的 suppressedFields。 在调试期间我可以通过以下方式访问它:

((BindingResult)getModelAndView(result).getModelMap().get("org.springframework.validation.BindingResult.account")).getSuppressedFields()

当从 hasErrors() 方法调用时。

因此,为了确保不使用 id,我只是通过参数传递它,然后检查具有该名称的帐户(它是一个唯一字段)是否有另一个 id 值:

String notExistingId = "999";
String newUserName = "newUser";
this.mockMvc.perform(post("/customer/register")
        .param("id", notExistingId)
        .param("username", newUserName)
        .param("password", "123")
        .param("emailAddress", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e49745a53524f58597d5a505c5451135e5250" rel="noreferrer noopener nofollow">[email protected]</a>")
        .param("address.country", "RU")
        .param("address.city", "Nsk")
        .param("address.street", "Lenin"))
        .andExpect(model().hasNoErrors())
        .andExpect(view().name("redirect:/index.htm"));
Optional<Account> account = accountService.getAccount(newUserName);
assertTrue( "Account with the username should exist", account.isPresent());
assertNotSame("Account id should not be equal to the id we try to pass with parameters",
        Long.parseLong(notExistingId),
        account.get().getId());

关于java - Spring setDisallowedFields 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20018569/

相关文章:

java - Apache James 安装问题 - java.lang.UnsupportedClassVersionError :

javascript - 如何验证一组复选框并返回错误消息javascript

c# - ASP.net RegularExpressionValidator 即使输入无效也允许回发

java - Spring MVC @RequestMapping ...使用方法名称作为操作值?

spring - 从浏览器上传 csv 的 MultipartFile 读取数据

java - Eclipse - JUnit - : "Launching MyMavenModule". NullPointerException 期间发生内部错误

java - 如何在java中计算xml文件中的叶子元素

spring - 如何绕过重置 session 的到期时间

java - Spring 执行器即使设置server.servlet.contextPath后也会显示404 Not found错误

javascript - 用于输入数字和逗号的正则表达式