【发布时间】:2019-04-21 17:23:07
【问题描述】:
我的问题是: @ModelAttribute 如果请求参数和表单字段具有相同的名称,则从请求参数而不是表单 DTO 填充表单字段。
示例:我有一个输入字段名为 name 的表单:
<input type="text" name="name" />
给定表单的值 name=John,
如果我使用 url 提交表单(网络方法 POST):
http://localhost:8080/user/?name=Michael
我将有同名的查询参数和表单字段。
我期望的是:名称字段应该从表单字段中填充,而不是查询参数。
MyForm.java
public class MyForm {
private String name;
private Boolean isMale;
private Byte status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsMale() {
return isMale;
}
public void setIsMale(Boolean isMale) {
this.isMale = isMale;
}
public Byte getStatus() {
return status;
}
public void setStatus(Byte status) {
this.status = status;
}
}
MyController.java
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/", method = RequestMethod.POST)
public String index(
Model model,
@ModelAttribute("form") MyForm form,
BindingResult bindingResult) {
String name = form.getName(); //this contains value from form: Michael
Boolean isMale = form.getIsMale(); //this contains value from query parameter: true
Byte status= form.getStatus(); //this contains value from form: 1
return "views/index";
}
当我提交带有值的表单时:
name = Michael
isMale = false
status = 1
使用带有查询参数的 url:
http://localhost:8080/user/?isMale=true
然后isMale 将包含值true,从查询参数填充。
我期望的是,isMale 应该包含从表单字段填充的false。
如何解决这个问题...?
【问题讨论】:
标签: java spring spring-boot spring-mvc modelattribute