gpt4 book ai didi

java - Spring setDisallowedFields 不工作

转载 作者:行者123 更新时间:2023-11-30 09:15:15 26 4
gpt4 key购买 nike

注册 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", "testIgnored@gmail.com")
.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 不会将不允许的字段视为错误。它只是将它们作为 suppressedFields 存储在 BindException 中。在调试期间,我可以通过以下方式访问它:

((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", "testIgnored@gmail.com")
.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com