(Edited for clarification) I have a POJO (SessionStorage) for storing session related data that I want to populate after successful authentication. Since I set Scope to "session", I expect MainController and AuthenticationSuccesshandler to use the same instance of the object.
When I start WebApp, the main controller initiates the instance (as expected), but when I log in, the AuthenticationSuccesshandler does not seem to have an auto-update of the SessionStorage object, because it throws a NullPointerException.
How do I get him to do what I want? Here are excerpts from my code:
@Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class SessionStorage implements Serializable{ long id; public int getId() { return id; } public SessionStorage() { System.out.println("New Session Storage"); id = System.currentTimeMillis(); } }
The main controller is as follows:
@Controller @Scope("request") @RequestMapping("/") public class MainController { @Autowired private SessionStorage sessionStorage; @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login( @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { System.out.println(sessionStorage.getId()); //Works fine ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("msg", "You've been logged out successfully."); } model.setViewName("login"); return model; } }
AuthentificationSuccesshandler (where the error occurs):
public class AuthentificationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private SessionStorage sessionStorage; @Override public void onAuthenticationSuccess(HttpServletRequest hsr, HttpServletResponse hsr1, Authentication a) throws IOException, ServletException { System.out.println("Authentication successful: " + a.getName()); System.out.println(sessionStorage.getId());
Relevant part of spring -security.xml:
<beans:bean id="authentificationFailureHandler" class="service.AuthentificationFailureHandler" /> <beans:bean id="authentificationSuccessHandler" class="service.AuthentificationSuccessHandler" /> <http auto-config="true" use-expressions="true"> <intercept-url pattern="/secure/**" access="hasRole('USER')" /> <form-login login-page="/login" default-target-url="/index" authentication-failure-handler-ref="authentificationFailureHandler" authentication-failure-url="/login?error" authentication-success-handler-ref="authentificationSuccessHandler" username-parameter="username" password-parameter="password" /> <logout logout-success-url="/login?logout" /> <csrf/> </http>
web xml:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>