How can I get an object from a model in the controller using Spring MVC 3?

I have a controller with a method that processes incoming data GET, stores some things in model, and then redirects to another page that deals with these objects.

I cannot find a good way to return the object stored in the first method back from the model to use it in the second method. How can i do this?

Here's the top of the controller:

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

Here is the code that adds the objects that I am after the model:

@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";
}
+5
source share
3 answers

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

, . ?

+1

One possible solution is to use @ModelAttribute, although this is pretty ugly, since you need to disable data binding for this attribute (for security):

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

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

All Articles