目录html
上一篇: spring security实现记住我下次自动登陆功能java
spring security提供了一个接口 AuthenticationSuccessHandler,该接口中只有一个方法,用来进行登陆成功后的操做git
public interface AuthenticationSuccessHandler { /** * Called when a user has been successfully authenticated. * * @param request the request which caused the successful authentication * @param response the response * @param authentication the <tt>Authentication</tt> object which was created during * the authentication process. */ void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException; }
咱们能够经过实现该接口来自定义登陆成功后的操做,但spring security提供了一个SavedRequestAwareAuthenticationSuccessHandler
实现类,这个实现类能够记住用户未登陆前要访问的地址,这样登陆成功后就能够把用户再跳转到他想去的页面。因此咱们通常使用继承这个类的方式来实现自定义登陆后续操做的功能。spring
自定义AuthenticationSuccessHandler接口的实现类,继承SavedRequestAwareAuthenticationSuccessHandler类,并加入到spring容器中ssh
@Component("loginSuccessHandler") public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Autowired private IUserDao userDao; public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { //记录相关的用户信息,如上次登陆时间 String name = authentication.getName(); userDao.updateLastLonginTime(System.currentTimeMillis(),name); //调用父类的方法把用户引导到未登陆前要去的页面 super.onAuthenticationSuccess(request,response,authentication); } }
其中remember-me-parameter="remembermeParamater"
指定前台传递的是否rememberme的参数名,前台要传递的参数值是true或false测试
<!--自定义登陆页面--> <security:form-login login-page="/login.html" login-processing-url="/login" username-parameter="username" password-parameter="password" authentication-failure-forward-url="/failed.html" default-target-url="/index.html" authentication-success-handler-ref="loginSuccessHandler" />
实例上就是在定义自定义登陆页面的标签内指定authentication-success-handler-ref="loginSuccessHandler"
,其中loginSuccessHandler是自定义的这个bean在容器中的名称url
启动工程,进行登陆,登陆成功后会更新用户表中的last_login_time
字段。code
须要注意的是若是是经过readme进行的登陆,不会更新当前用户的登陆时间,只有经过帐号密码登陆时才会进行更新,也就是只有这时才会执行这个onAuthenticationSuccess方法orm
在用户登陆成功后记录本次登陆相关的信息,须要继承spring-security提供的SavedRequestAwareAuthenticationSuccessHandler
类,重写其中的onAuthenticationSuccess方法,在其中进行记录用户信息的操做,在方法的最后调用父类的方法把用户引导到未登陆前要去的页面。xml
测试工程代码的地址:工程示例