【问题标题】:Spring MVC binding overriding value attribute on form input表单输入上的 Spring MVC 绑定覆盖值属性
【发布时间】:2013-07-10 10:38:34
【问题描述】:

我有一个将数据发布到 Inquiry 对象的表单。 Inquiry 对象是 Controller 中的 ModelAttribute,它没有明确定义的构造函数。尽管在我的表单中将 age 输入元素的 value 属性设置为空字符串,但它仍然为零。这让我觉得它从 Inquiry 对象中获取了 age 的现有值,我们将其初始化为零。有没有办法仍然可以发布到 enquiry.age 但不在我的页面上显示它的当前值?

我的表格

<form:form commandName="enquiry" method="post" action="mycontext/jsp/enquiry-search">
    <form:input path="name" value=""/>
    <form:input path="age" value=""/>
</form:form>

我的控制器的一部分

    @RequestMapping( value = "/enquiry/{screenType}", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseStatus( HttpStatus.OK )
public String getEnquiryScreen(@ModelAttribute ("enquiry") Enquiry enquiry, @PathVariable("screenType") String screenType) {

    return "enquiry";
}

@ModelAttribute( "enquiry" )
public Enquiry getEnquiry() {
    return new Enquiry();
}

我的查询课

public class Enquiry {

private String name;
private int age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

【问题讨论】:

    标签: java jsp spring-mvc


    【解决方案1】:

    Thats not how model attributes work.

    如果您将查询作为模型属性,则您的表单实际上什么都不做。

    我将有两种方法,一种用于获取,一种用于发布,然后 POST 可以将 Inquiry 作为带有 ModelAttribute anaotion 的方法参数。这将确保对象是从请求中计算出来的,而不是使用模型属性注释的方法——它只是实例化一个新实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2015-11-04
      • 2013-04-04
      • 2010-09-22
      • 2018-07-12
      相关资源
      最近更新 更多