Spring 自定义登录页面
Contents
1. 简介
**在本文中,我们将了解如何为返回我们应用程序的用户开发自定义登录页面。**用户将收到标准的“欢迎…”消息。
2. 添加长期cookie
**识别用户是否返回我们网站的一种方法是在用户成功登录后添加一个长期存在的 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);
return welcomeCookie;
}
我们设置了一个带有键*“welcome”的cookie,值是当前用户的firstName*。cookie 设置为 30 天后过期。
3. 读取登录表单上的 Cookie
最后一步是在登录表单加载时读取 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}">Email</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 = "Welcome " + username + "!";
}
}
第一个函数只是读取用户登录时设置的 cookie。第二个函数操作 HTML 文档以设置欢迎消息(如果存在 cookie)。
在HTML <body>标签的onload事件上调用函数display_username() :
<body onload="display_username()">