(为澄清起见,进行了编辑)我有一个POJO(SessionStorage)来存储特定于 session 的数据,我想在成功进行身份验证后填充这些数据。由于我将Scope设置为“session”,因此我希望MainController和AuthenticationSuccesshandler使用相同的对象实例。
当我运行WebApp时,主 Controller 将启动一个实例(按预期方式),但是当我登录时,AuthenticationSuccesshandler似乎没有 Autowiring 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 如下所示:
@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>
最佳答案
这个问题很旧,但是显示为我在Google中问题的第一个链接之一。
我发现最有效的解决方法是在自定义AuthenticationSuccessHandler上设置Scope。
@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
可以在此处找到更多详细信息:
https://tuhrig.de/making-a-spring-bean-session-scoped/