davioooh
davioooh

Reputation: 24706

Spring MVC Model life-cicle

I have a doubt about Model behavior in Spring MVC.

I have a controller class with to handler methods, say:

@RequestMapping(value = "/result", method = RequestMethod.GET)
public String getExportResults(@RequestParam("token") String token,
        Model model) {

        // ...

        model.addAttribute("task", myObject);

        // ...
}

@RequestMapping(value = "/file", method = RequestMethod.GET)
public void getFile(Model model, HttpServletResponse response)

    // can't find "task" attribute...

}

When I put the "task" attribute into model, in my getExportResults I expect to find it into model argument of getFile method, but when I try to get it, "task" is null. Am I wrong? Maybe model behaviour is not clear to me...

Upvotes: 3

Views: 3254

Answers (2)

JB Nizet
JB Nizet

Reputation: 692023

Your expectations are wrong. Putting something in the model makes it available for the current request only. The goal of adding something into the model is to make it available for the view, in order to generate the HTML page.

Upvotes: 5

fmucar
fmucar

Reputation: 14558

Model is initialized with every request, each request creates a new model object. The model you are adding your task object is not the same model object you get in getFile method.

If those are 2 different request, which seems like, you may want to put the task object into session and retrieve it from there.

Upvotes: 1

Related Questions