【问题标题】:How can I get an object out of the model in the controller with Spring MVC 3?如何使用 Spring MVC 3 从控制器中的模型中获取对象?
【发布时间】:2011-09-12 14:14:47
【问题描述】:

我有一个控制器,它的方法处理传入的GET 数据,在model 中存储一些东西,然后重定向到处理这些对象的另一个页面。

我似乎找不到任何好的方法将存储在第一种方法中的对象从模型中取出以用于第二种方法。我该怎么做?

这是控制器的顶部:

@Controller
@RequestMapping("/reviews")
@SessionAttributes({"review", "externalReview"})
public class ReviewController {
    // [SNIP]
}

这是将我所追求的对象添加到模型中的代码:

@RequestMapping(value="/new", params="UName", method=RequestMethod.GET)
public String newFormFromExternal(@ModelAttribute("externalReview") ExternalReview externalReview, Model model) throws IncompleteExternalException {
    // Convert the inbound external
    Review fromExternal = ExternalReviewUtil.reviewFromExternalReview(externalReview, externalDAO);

    // Add the externalReview to the session so we can look to see if we got a reviewee on the way in
    model.addAttribute("externalReview", externalReview);

    model.addAttribute("review", fromExternal);

    return "redirect:/reviews/newFromExternal";
}

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    你很幸运。

    如果您正在使用或有能力更新到新发布的 Spring 3.1,您可以使用新范围的 Flash 变量。

    http://static.springsource.org/spring/docs/3.1.0.RC1/spring-framework-reference/html/mvc.html#mvc-flash-attributes

    如果您不能使用 3.1,您可能可以自己实现该解决方案。本质上,您希望捕获重定向中需要存在的模型对象,放入会话中,并在检索到它后将其删除以防止会话膨胀。

    【讨论】:

      【解决方案2】:

      目前,我只是得到模型的Map,通过它的键(String 名称)获取我想要的对象,然后将它转换为它真正的对象(而不仅仅是 @ 987654323@)。

      代码如下:

      @RequestMapping(value="/newFromExternal", method=RequestMethod.GET)
      public String newExternalForm(Model model) {
          // Get the review from the model
          Review review = (Review) model.asMap().get("review");
      
          /*** Do stuff with the review from the model ****/
      
          return "reviews/newFromPacs";
      }
      

      这种方式可行,但看起来很笨拙。这真的是唯一的方法吗?

      【讨论】:

      • @axtavt - 是的,我编辑了问题以显示控制器类定义。
      【解决方案3】:

      一种可能的解决方案是使用@ModelAttribute,尽管它非常难看,因为您需要禁用该属性的数据绑定(出于安全考虑):

      @RequestMapping(value="/newFromExternal", method=RequestMethod.GET) 
      public String newExternalForm(@ModelAttribute Review review) {
          ...
      }
      
      @InitBinder("review")
      public void disableReviewBinding(WebDataBinder b) {
          b.setAllowedFields();
      }
      

      【讨论】:

      • 不幸的是,禁用该属性上的数据绑定会变得非常难看,因为我需要让用户填写缺失的数据(这是第二种方法处理的内容),所以在以后绑定它@987654323 @方法是当前的流程。但是,这比我目前拥有的更干净(在某种程度上)。
      猜你喜欢
      • 2016-11-12
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多