Spring MVC 在表单提交时构造一个子对象,而它不应该



我遇到了一个问题,即即使我的表单没有指定应该创建一个子对象,也要构造一个子对象。我遇到的问题是,在提交表格时,在声明二级学生的姓氏和名字不存在时,存在验证字段错误。

理想情况下,我希望secondary保持为空,因此在提交表单时不进行验证。

HTML表单(为了简单起见,进行了剪切(:

<form th:action="@{/quotes/save}" th:object="${quote}">
<input type="text" th:field="*{primary.lastName}" />
<input type="text" th:field="*{primary.firstName}" />
</form>

Quote对象:

@Entity    
public class Quote {
@ManyToOne
@Valid
@NotNull(groups={Quote.ValidationPrimary.class})
private Person primary;
@ManyToOne
@Valid
private Person secondary;
}

Person对象:

@Entity
public class Person {
@NotEmpty
private String lastName;
@NotEmpty
private String firstName;
}

报价控制器:

@Controller
public class QuoteController {
@PostMapping("/quotes/save")
public String save(@ModelAttribute @Validated({Quote.ValidationPrimary.class}) Quote quote, BindingResult bindingResult) {
quote.getPrimary(); // this contains a Person object... as expected
quote.getSecondary(); // this also contains a Person object... which is NOT EXPECTED
...
}
}

使用th:object时不要使用名称,而是使用th:field。你的控制器和我平时看到的有点不同。我建议将其更改为以下代码。

表单

<form th:action="@{/quotes/save}" th:object="${quote}">
<input type="text" th:field="*{primary.lastName}" />
<input type="text" th:field="*{primary.firstName}" />
</form>

控制器

@PostMapping("/quotes/save")
public String save(@ModelAttribute Quote quote, BindingResult bindingResult) {
quote.getPrimary(); // this contains a Person object... as expected
quote.getSecondary(); // this also contains a Person object... which is NOT EXPECTED
...
}
}

最新更新