Spring MVC 3命令对象值在GET和POST操作之间丢失


问题内容

我的域对象不保留在同一控制器上的GET和POST操作之间的JSP文件中未明确引用的值。这是一个省略了错误检查的示例

我有一个域对象。

class foo
{
    private int fieldA;
    private String fieldB;
    // .. getters and setters omitted
}

控制者

@Controller
public class MyController
{
@Autowired
private IDaoService daoService;

@RequestMapping(value = "/display", method = RequestMethod.GET)
public String newForm(@RequestParam("id") Long id, Model model, Principal principal) throws Exception
{
    // check that the user has permissions
    ...

    // get the object
    Foo foo = daoService.read(id);
    // at this point foo.fieldA is equal to the input id
    model.addAttribute("foo", foo);

    // return the JSP path
}

@RequestMapping(value="/update", method = RequestMethod.POST)
public String update(@ModelAttribute("foo") Foo foo,
        BindingResult result, 
        Principal principal,
        Model model) throws Exception

{   
    // ERROR - at this point, fieldA is null

}
}

JSP

    <form:form  method="post" commandName="foo">
        <fieldset>
            <legend>Invest</legend>
            <div class="fm-req">
                <label for="fm-name">Field B</label>    
                <spring:bind path="fieldB">
                    <input id="fm-name" type="text" name="${status.expression}" value="${status.value}" ></input>
                </spring:bind>
            </div>
            <div id="fm-submit" class="fm-req">
                <INPUT type="submit" value="Submit" name="Submit" />        
            </div>
        </fieldset>
    </form:form>

我以为JSP会在newForm中创建具有fieldA
set(可能还有fieldB)的对象。用户可以选择更改fieldB,然后单击“提交”。我已经大量阅读了Spring文档并检查了Web站点,但是无法找出为什么foo.fieldA在控制器的update方法上为null的原因。

根据我对Spring MVC的了解,这似乎是一种标准模式,但是请随时纠正我。

提前致谢,


问题答案:

那是预期的行为。

对象的两个实例(in newFormupdatefoo (在Java类名称中应以大写字母开头) 彼此完全独立。

因此,Auger创建一个隐藏字段,或将其放入会话中。我建议隐藏字段: