Spring security如何实现记录用户登录时间功能
一、原理分析
spring security提供了一个接口 AuthenticationSuccessHandler,该接口中只有一个方法,用来进行登录成功后的操作
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实现类,这个实现类可以记住用户未登录前要访问的地址,这样登录成功后就可以把用户再跳转到他想去的页面。所以我们一般使用继承这个类的方式来实现自定义登录后续操作的功能。
二、实现方式
2.1 自定义AuthenticationSuccessHandler实现类
自定义AuthenticationSuccessHandler接口的实现类,继承SavedRequestAwareAuthenticationSuccessHandler类,并加入到spring容器中
@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
2.2 在spring-security的配置文件中指定自定义的AuthenticationSuccessHandler
<!--自定义登录页面-->
<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在容器中的名称
2.3 测试
启动工程,进行登录,登录成功后会更新用户表中的last_login_time字段。

需要注意的是如果是通过readme进行的登录,不会更新当前用户的登录时间,只有通过账号密码登录时才会进行更新,也就是只有这时才会执行这个onAuthenticationSuccess方法
三、总结
在用户登录成功后记录本次登录相关的信息,需要继承spring-security提供的SavedRequestAwareAuthenticationSuccessHandler类,重写其中的onAuthenticationSuccess方法,在其中进行记录用户信息的操作,在方法的最后调用父类的方法把用户引导到未登录前要去的页面。
测试工程代码的地址:工程示例
上一篇:@ConfigurationProperties绑定配置信息至Array、List、Map、Bean的实现
栏 目:JAVA代码
本文标题:Spring security如何实现记录用户登录时间功能
本文地址:http://www.codeinn.net/misctech/139495.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




