Search code examples
javaspringspring-mvcsessionmodelattribute

@SessionAttributes not working properly for consecutive get requests


Before asking question first i describe the scenario. I have multiple servlet contexts. suppose /**book**/review url is corresponding to book-servlet.xml and /**report**/update corresponds to report-servlet.xml.

Here are two controllers

@Controller
@SessionAttributes(BookController.COMMAND_NAME)
public class BookController {

    public static final String COMMAND_NAME = "login";

    @GetMapping("/book/review")
    public String show(ModelMap modelMap) {

        modelMap.put(COMMAND_NAME, getBook());

        return "redirects:" + "/report/update"; //it redirects to second controller method
    }
}

@Controller
@SessionAttributes(ReportController.COMMAND_NAME)
public class ReportController {

    public static final String COMMAND_NAME = "report";

    @GetMapping("/report/update")
    public String show(ModelMap modelMap) {

        modelMap.put(COMMAND_NAME, getReport());

        return "redirects:" + "/report/done";
    }
}

Observe this two controller. When i put getBook() in model it stores this object in session after method excution since @SessionAttributes(BookController.COMMAND_NAME) is added above class definition. But, after redirection to /report/update (different servlet context) we are also trying to put getReport() in model. And after handler method excution spring should put the object in session as it does for first case.Unfortunately for second controller it doesn't store it in session.

My question is if the first controller method can successfully save it in session why the second controller can't? Or is it for servlet context switching / multiple get requests or something like this. Please i need to know the reason it behaves weirdly. I am now totally confused about @SessionAttributes. It should work same for both controllers.


Solution

  • After studying on this i found that it is wise to use RedirectAttributes for this type of redirect scenario. Cause ModelMap is intended for scenario where you use this ModelMap attributes to rendering a view. And FlashAttribute will survive after immediate redirection to another handler method and then be erased. So, i did my solution using RedirectAttrinute support from spring.