簡體   English   中英

如何使用Spring MVC 3在控制器中從模型中獲取對象?

[英]How can I get an object out of the model in the controller with Spring MVC 3?

我有一個控制器,它有一個方法來處理傳入的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";
}

你很幸運。

如果您正在使用或有能力更新到新發布的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,你可能自己實現解決方案。 基本上,您希望捕獲重定向中所需的模型對象,放入會話中,並在檢索后將其刪除,以防止會話膨脹。

目前,我只是獲取模型的Map ,通過它的鍵( String名稱)獲取我想要的對象,然后將其轉換為它真正的對象(而不僅僅是Object )。

這是代碼:

@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";
}

這種方式有效,但看起來很笨拙。 這真的是唯一的方法嗎?

一種可能的解決方案是使用@ModelAttribute ,雖然它非常難看,因為您需要為該屬性禁用數據綁定(為了安全性):

@RequestMapping(value="/newFromExternal", method=RequestMethod.GET) 
public String newExternalForm(@ModelAttribute Review review) {
    ...
}

@InitBinder("review")
public void disableReviewBinding(WebDataBinder b) {
    b.setAllowedFields();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM