Spring MVC ModelAttribute值丢失了

时间:2018-02-22 22:05:40

标签: java spring model-view-controller

我遇到了我的模型属性在页面之间丢失值的情况。

我有两个控制器方法分别处理GET和POST请求。

获取方法

@RequestMapping(value = "/checkout/billing", method = RequestMethod.GET)
    public String getBillingPage(Model model, final HttpServletRequest request) throws CMSItemNotFoundException {
   // other code

   checkoutForm.setCustomFieldsForm(customFieldsForm);
   model.addAttribute("checkoutForm", checkoutForm);

   // other code
}

GET方法完成后的调试视图 enter image description here

POST方法

@RequestMapping(value = "/checkout/billing", method = RequestMethod.POST)
    public String submitPayment(
            @Valid @ModelAttribute("checkoutForm") final CheckoutForm checkoutForm,
            final BindingResult bindingResult,
            Model model,
            final HttpServletRequest request,
            final HttpServletResponse response) throws CMSItemNotFoundException 
    {}
调用POST方法时

调试视图 enter image description here

1234来自用户在表单字段中输入该数据。其他值应该仍然存在但不是null。

这里可能会发生什么?

1 个答案:

答案 0 :(得分:2)

您的模型未存储在会话中。每个请求都会创建一个新的模型对象这就是为什么它是空的。

您可以将模型添加为会话属性。请在此处找到https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-sessionattrib

的文档