2

我正在编写一个类似向导的控制器来处理跨多个视图的单个 bean 的管理。我使用 @SessionAttributes 来存储 bean,并使用 SessionStatus.setComplete() 在最终调用中终止会话。但是,如果用户放弃向导并转到应用程序的另一部分,我需要强制 Spring 在他们返回时重新创建 @ModelAttribute。例如:

@Controller
@SessionAttributes("commandBean")
@RequestMapping(value = "/order")
public class OrderController
{
  @RequestMapping("/*", method=RequestMethod.GET)
  public String getCustomerForm(@ModelAttribute("commandBean") Order commandBean)
  {
    return "customerForm";
  }

  @RequestMapping("/*", method=RequestMethod.GET)
  public String saveCustomer(@ModelAttribute("commandBean") Order commandBean, BindingResult result)
  {
    [ Save the customer data ];
    return "redirect:payment";
  }

  @RequestMapping("/payment", method=RequestMethod.GET)
  public String getPaymentForm(@ModelAttribute("commandBean") Order commandBean)
  {
    return "paymentForm";
  }

  @RequestMapping("/payment", method=RequestMethod.GET)
  public String savePayment(@ModelAttribute("commandBean") Order commandBean, BindingResult result)
  {
    [ Save the payment data ];
    return "redirect:confirmation";
  }

  @RequestMapping("/confirmation", method=RequestMethod.GET)
  public String getConfirmationForm(@ModelAttribute("commandBean") Order commandBean)
  {
    return "confirmationForm";
  }

  @RequestMapping("/confirmation", method=RequestMethod.GET)
  public String saveOrder(@ModelAttribute("commandBean") Order commandBean, BindingResult result, SessionStatus status)
  {
    [ Save the payment data ];
    status.setComplete();
    return "redirect:/order";
  }

  @ModelAttribute("commandBean")
  public Order getOrder()
  {
    return new Order();
  }
}

If a user makes a request to the application that would trigger the "getCustomerForm" method (i.e., http://mysite.com/order), and there's already a "commandBean" session attribute, then "getOrder" is not called. I need to make sure that a new Order object is created in this circumstance. Do I just have to repopulate it manually in getCustomerForm?

Thoughts? Please let me know if I'm not making myself clear.

4

1 回答 1

0

Yes, sounds like you may have to repopulate it manually in getCustomerForm - if an attribute is part of the @SessionAttributes and present in the session, then like you said @ModelAttribute method is not called on it.

An alternative may be to define a new controller with only getCustomerForm method along with the @ModelAttribute method but without the @SessionAttributes on the type so that you can guarantee that @ModelAttribute method is called, and then continue with the existing @RequestMapped methods in the existing controller.

于 2012-07-29T01:08:23.220 回答