棄用常量的文檔準確地告訴你應該做的:
/**
* @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler}
*/
@Deprecated
public static final String SPRING_SECURITY_LAST_USERNAME_KEY =
"SPRING_SECURITY_LAST_USERNAME";
事情是這樣的:
public class UserNameCachingAuthenticationFailureHandler
extends SimpleUrlAuthenticationFailureHandler {
public static final String LAST_USERNAME_KEY = "LAST_USERNAME";
@Autowired
private UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter;
@Override
public void onAuthenticationFailure(
HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception)
throws IOException, ServletException {
super.onAuthenticationFailure(request, response, exception);
String usernameParameter =
usernamePasswordAuthenticationFilter.getUsernameParameter();
String lastUserName = request.getParameter(usernameParameter);
HttpSession session = request.getSession(false);
if (session != null || isAllowSessionCreation()) {
request.getSession().setAttribute(LAST_USERNAME_KEY, lastUserName);
}
}
}
在您的安全配置:
<security:http ...>
...
<security:form-login
authentication-failure-handler-ref="userNameCachingAuthenticationFailureHandler"
...
/>
</security:http>
<bean
id="userNameCachingAuthenticationFailureHandler"
class="so.UserNameCachingAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/url/to/login?error=true"/>
</bean>
在登錄.jsp:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %>
...
<%--in the login form definition--%>
<input id="j_username" name="j_username" type="text"
value="<c:out value="${sessionScope.LAST_USERNAME}"/>"/>
非常感謝!它像需要的那樣工作! – droidpl 2013-02-24 16:21:58
沒問題。請注意,有些地方還有改進空間。例如。在.jsp中對會話屬性的名稱進行硬編碼並不優雅。理想情況下,它應該引用在'UserNameCachingAuthenticationFailureHandler'中定義的常量。 (我不得不讚嘆我不知道如何實現這種間接。) – zagyi 2013-02-24 16:27:21
我不知道這可以實現!但現在這就是我所需要的,這不是安全性,而是讓用戶生活更美好的一個小訣竅!我不可能在任何地方找到另一種簡單的解決方案,這是不可思議的! ;) – droidpl 2013-02-24 16:43:33