1. 引言

本文是 Spring Security 注册系列 的延续。

本文将探讨如何为返回应用的用户开发自定义登录页面,实现个性化欢迎信息展示。 当用户再次访问时,系统将显示标准的“欢迎...”消息。

识别返回用户的一种有效方式是在用户成功登录后设置长期 Cookie(例如有效期30天)。 要实现此逻辑,我们需要自定义 AuthenticationSuccessHandler,在认证成功时添加 Cookie。

创建自定义处理器 MyCustomLoginAuthenticationSuccessHandler 并实现 onAuthenticationSuccess() 方法:

@Override
public void onAuthenticationSuccess(final HttpServletRequest request,
  final HttpServletResponse response, final Authentication authentication)
  throws IOException {
    addWelcomeCookie(gerUserName(authentication), response);
    redirectStrategy.sendRedirect(request, response,
    "/homepage.html?user=" + authentication.getName());
}

核心逻辑在于调用 addWelcomeCookie() 方法。

查看添加 Cookie 的具体实现:

private String gerUserName(Authentication authentication) {
    return ((User) authentication.getPrincipal()).getFirstName();
}

private void addWelcomeCookie(String user, HttpServletResponse response) {
    Cookie welcomeCookie = getWelcomeCookie(user);
    response.addCookie(welcomeCookie);
}

private Cookie getWelcomeCookie(String user) {
    Cookie welcomeCookie = new Cookie("welcome", user);
    welcomeCookie.setMaxAge(60 * 60 * 24 * 30); // 30天有效期
    return welcomeCookie;
}

我们设置了:

  • ✅ Cookie 键名为 "welcome"
  • ✅ 值为当前用户的 firstName
  • ✅ 有效期设为30天(60*60*24*30秒)

最后一步是在登录页面加载时读取 Cookie,如果存在则提取用户名显示欢迎信息。通过 Javascript 可轻松实现。

首先在登录页面添加占位符 *welcometext*:

<form name='f' action="login" method='POST' onsubmit="return validate();">
    <span id="welcometext"> </span>
                 
    <br /><br />
    <label class="col-sm-4" th:text="#{label.form.loginEmail}">邮箱</label>
    <span class="col-sm-8">
      <input class="form-control" type='text' name='username' value=''/>
    </span>
    ...
</form>

对应的 Javascript 实现:

function getCookie(name) {
    return document.cookie.split('; ').reduce((r, v) => {
        const parts = v.split('=')
        return parts[0] === name ? decodeURIComponent(parts[1]) : r
    }, '')
}
    
function display_username() {
    var username = getCookie('welcome');
    if (username) {
        document.getElementById("welcometext").innerHTML = "欢迎回来 " + username + "!";
    }
}

两个函数分工:

  • ⚠️ getCookie():解析并读取登录时设置的 Cookie
  • display_username():检测 Cookie 存在时动态更新欢迎信息

HTML 标签的 onload 事件中调用:

<body onload="display_username()">

4. 总结

本文展示了通过修改 Spring 默认认证流程,快速实现用户体验定制的方案。基于这个简单配置,可以扩展出更复杂的个性化功能。

示例登录页面可通过 /customLogin 接口访问。完整代码请参考 GitHub 项目


原始标题:Custom Login Page for Returning User

« 上一篇: Apache Commons CSV 介绍
» 下一篇: Reladomo 框架详解