9.4.1 添加自定义的登录页

创建自定义登录页的第一步就是了解登录表单中都需要些什么。只需看一下默认登录页面的 HTML 源码,我们就能了解需要些什么:

<html>
  <head><title>Login Page</title></head>
  <body onload='document.f.username.focus();'>
  <h3>Login with Username and Password</h3>  
  <form name='f' th:action='/spittr/login' method='POST'>
   <table>
    <tr><td>User:</td><td>
        <input type='text' name='username' value='' /></td></tr>
    <tr><td>Password:</td>
        <td><input type='password' name='password'/></td></tr>
    <tr><td colspan='2'>
        <input name="submit" type="submit" value="Login"/></td></tr>
    <input name="_csrf" type="hidden" value="5sdf4-dfsd45s-4579-sdhf564fds45" />
    </table>
  </form>
  </body>
</html>

需要注意的一个关键点是提交到了什么地方。同时还需要注意 username 和 password 输入域,在你的登录页中,需要同样的输入域。最后,假设没有禁用 CSRF 的话,还需要保证包含了值为 CSRF token 的 "_csrf" 输入域。

如下程序清单所展现的 Thymeleaf 模板提供了一个与 Spittr 应用风格一致的登录页。

程序清单 9.8 为 Spittr 应用编写的自定义登录页(以 Thymeleaf 模板的形式)
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spitter</title>
    <link rel="stylesheet" 
          type="text/css" 
          th:href="@{/resources/style.css}"></link>
  </head>
  <body onload='document.f.username.focus();'>
    <div id="header" th:include="page :: header"></div>

  <div id="content">
  
    <a th:href="@{/spitter/register}">Register</a>
  
  
  <form name='f' th:action='@{/login}' method='POST'>
   <table>
    <tr><td>User:</td><td>
        <input type='text' name='username' value='' /></td></tr>
    <tr><td>Password:</td>
        <td><input type='password' name='password'/></td></tr>
    <tr><td colspan='2'>
    <input id="remember_me" name="remember-me" type="checkbox"/>
    <label for="remember_me" class="inline">Remember me</label></td></tr>
    <tr><td colspan='2'>
        <input name="submit" type="submit" value="Login"/></td></tr>
   </table>
  </form>
  </div>
  <div id="footer" th:include="page :: copy"></div>
  </body>
</html>

需要注意的是,在 Thymeleaf 模板中,包含了 username 和 password 输入域,就像默认的登录页一样,它也提交到了相对于上下文的 “/login” 页面上。因为这是一个 Thymeleaf 模板,因此隐藏的 “_csrf” 域将会自动添加到表单中。

Last updated