I am writing a web application using SpringMVC. I would like to save some data in the session until the user logs out. I used to do this with @SessionAttributes("someData") , but then I had to put @ModelAttribute("someData") someDataType someData as an argument for each query matching method. So here is what I did:
My AccessData class:
@Component @Scope(value = "session") public class AccessData { private long userID; private String userKey; public AccessData(long ID, String key) { this.userID = ID; this.userKey = key; } public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getUserKey() { return userKey; } public void setUserKey(String userKey) { this.userKey = userKey; } }
The first controller (here I get and check the user input from the form):
@Controller @Scope(value = "session") public class LoginController { @ModelAttribute("accessData") public AccessData getAccessData() { return this.accessData; } private Utils utilsService; private LoginService loginService; @Autowired private AccessData accessData; @Autowired public LoginController(LoginService loginService, Utils utils) { this.loginService = loginService; this.utilsService = utils; } @RequestMapping(value = ControllerPaths.LOGIN, method = RequestMethod.POST) public ModelAndView showLoginStatus( @ModelAttribute(LOGINDATA) LoginData loginData) { try { accessData = loginService.validateLoginData(loginData); } catch (IncorrectLoginDataException e) { logger.trace("Showing fail login screen..."); return utilsService.getShowView(ViewPaths.LOGIN_FAIL); } catch (HTTPException e) { return utilsService.getShowViewWithStringAttribute( ViewPaths.INFO_VIEW, MESSAGE, CONNECTION_ERROR); } return utilsService.getShowView(ViewPaths.LOGIN_SUCCESS); } }
Second controller:
@Controller @Scope(value = "session") public class SecondController { @ModelAttribute("accessData") public AccessData getAccessData() { return this.accessData; } private Utils utilsService; private LoginService loginService; @Autowired private AccessData accessData; @Autowired public SecondController(LoginService loginService, Utils utils) { this.loginService = loginService; this.utilsService = utils; } @RequestMapping(value = ControllerPaths.SHOW_ACCESS_DATA, method = RequestMethod.GET) public ModelAndView showAccessData( System.out.println(accessData.getUserKey()); return utilsService.getShowView(ViewPaths.INDEX); } }
The problem is that when I print the userKey value in the second controller, the value is null. I checked if I get the correct data from the server in LoginController , and that is normal. So what am I doing wrong? Thanks in advance for your help
source share