网上搜索一大圈,最后发现http://www.ke-cai.net/2010/11/auto-login-after-successful.html里讲述的是最接近答案的,但一测试,发现验证是通过了,session却没有保存,接着再搜,发现了一篇文章说到了这个问题,http://stackoverflow.com/questions/5428654/spring-security-auto-login-not-persisted-in-httpsession,按照它提供的解决方法发现session能保存了。
最后要解决的一件事是验证失败处理,上面两篇文章都没说,参考spring security document解决了,最后代码如下:
在controller里边声明AuthenticationManager变量,这个是关键点:
@Autowired
@Qualifier(“org.springframework.security.authenticationManager”)
protected AuthenticationManager authenticationManager;
然后是当注册成功后的代码:
@RequestMapping(value = “/registermyuser”)
public ModelAndView registeruser(
Locale locale,HttpServletRequest request)
{
System.out.println(“register user”);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
“heda”, “111111”);
//request.getSession();
try{
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager
.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
}
catch( AuthenticationException e ){
System.out.println(“Authentication failed: ” + e.getMessage());
return new ModelAndView(new RedirectView(“register”));
}
return new ModelAndView(new RedirectView(“”));
}
就这样,测试成功了。
———————
作者:softwarehe
来源:CSDN
原文:https://blog.csdn.net/softwarehe/article/details/7708947
版权声明:本文为博主原创文章,转载请附上博文链接!