如何使用Spring MVC 3在控制器中从模型中获取对象?

cde*_*zaq 5 java spring spring-mvc

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

我似乎找不到任何好的方法来将第一个方法中存储的对象从模型中取出,以便在第二个方法中使用.我怎样才能做到这一点?

这是控制器的顶部:

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

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

@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";
}
Run Code Online (Sandbox Code Playgroud)

Roy*_*ouh 2

你很幸运。

如果您正在使用或有能力更新到新发布的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,您可能可以自己实现该解决方案。本质上,您希望捕获重定向中需要出现的模型对象,放入会话中,并在检索到它后将其删除,以防止会话膨胀。