It seems that when I attempt to call a URL with ModelAndView(), my session is ended and when the view is loaded, a new session is created without any of the data I hope to persist.
return new ModelAndView("redirect:http//.....)
Is there a better way to handle sessions besides @SessionAttributes when moving to different controllers?
@SessionAttributes
session objects are not meant to be shared among controllers. Here are some alternatives:
You can store attributes directly into HttpSession object. You can obtain HttpSession object by adding it to controller method as parameter:
public ModelAndView myControllerMethod(..., HttpSession session) {
...
session.setAttribute("someAttribute", someValue);
...
}
You can also autowire HttpSession object and then use it in controller methods:
@Autowired
private HttpSession httpSession;
You can create a session scoped bean and inject that bean into controllers that need it:
<bean id="mySessionDataBean" class="com.example.MySessionDataBeanImpl" scope="session">
<aop:scoped-proxy />
</bean>
And then use it in controllers (MySessionDataBeanImpl implements SessionDataBean interface in this example):
public class MyController {
....
@Autowired
SessionDataBean sessionDataBean;
@RequestMapping(...)
public ModelAndView controllerMethod(...) {
...
sessionDataBean.setSomeValue(someValue);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.