(编辑澄清)我有一个POJO(SessionStorage)来存储会话特定数据,我想在成功验证后填充它。由于我将Scope设置为" session",我希望MainController和AuthenticationSuccesshandler使用相同的对象实例。
当我运行WebApp时,主控制器启动一个实例(如预期的那样),但是当我登录时,AuthenticationSuccesshandler似乎没有自动装配SessionStorage对象,因为它会抛出NullPointerException。
我如何让它做我想要的?以下是我的代码的摘录:
@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();
}
}
主控制器如下所示:
@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(抛出错误的地方):
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()); //NullPointerException
}
}
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" />
<!-- enable csrf protection -->
<csrf/>
</http>
网络的XML:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
答案 0 :(得分:2)
这个问题已经陈旧,但却是我在谷歌问题的第一个链接之一。
我发现最有效的修复方法是在自定义AuthenticationSuccessHandler上设置Scope。
@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
更多细节可以在这里找到: https://tuhrig.de/making-a-spring-bean-session-scoped/