2

我有一个由 ThymeLeaf 呈现并由 Spring Security 提供支持的登录表单。如果发生身份验证错误,我希望用户名字段预先填充用户在上次尝试时输入的值。Spring Security 为此目的提供了 SPRING_SECURITY_LAST_USERNAME,但我对文档和在线的搜索并没有找到如何通过 ThymeLeaf 公开它。以下是相关文件的简化版本:

我的安全 XML 文件:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <sec:http auto-config="true">
        <sec:intercept-url pattern="/login/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <sec:form-login login-page="/login" authentication-failure-url="/login/fail" default-target-url="/"/>
        <sec:logout />
    </sec:http>
    <sec:global-method-security secured-annotations="enabled"/>
</beans>

登录.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head th:include="template::head"></head>
    <body class="login">
        <nav th:include="template::nav"></nav>
        <div>
            <h2>Log in</h2>
            <div>
                <div th:if="${loginFail}" class="error">
                    Username/password incorrect.
                </div>
                <form id="login" th:action="@{/j_spring_security_check}" method="POST">
                    <dl>
                        <dt>Username</dt>
                        <dd><input type="text" id="j_username" name="j_username" />@mshare.net</dd>
                        <dt>Password</dt>
                        <dd><input type="password" id="j_password" name="j_password" /></dd>
                    </dl>
                    <input type="submit" value="Log in" />
                </form>
            </div>
        </div>
    </body>
</html>

控制器错误处理程序:

@RequestMapping(value = "/login/fail")
public String loginError(Model model) {
    model.addAttribute("loginFail", Boolean.TRUE);
    return "login";
}
4

0 回答 0