第 4 章 自定义登陆页面

Spring Security虽然默认提供了一个登陆页面,但是这个页面实在太简陋了,只有在快速演示时才有可能它做系统的登陆页面,实际开发时无论是从美观还是实用性角度考虑,我们都必须实现自定义的登录页面。

4.1. 实现自定义登陆页面

自己实现一个login.jsp,放在src/main/webapp/目录下。
+ ch04/
  + src/
    + main/
      + resources/
        * applicationContext.xml
      + webapp/
        + WEB-INF/
          * web.xml
        * admin.jsp
        * index.jsp
        * login.jsp
    + test/
      + resources/
  * pom.xml
        

4.2. 修改配置文件

在xml中的http标签中添加一个form-login标签。
<http auto-config='true'>
    <intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login login-page="/login.jsp"authentication-failure-url="/login.jsp?error=true"default-target-url="/" />
</http>
        
1
让没登陆的用户也可以访问login.jsp。 [2]
这是因为配置文件中的“/**”配置,要求用户访问任意一个系统资源时,必须拥有ROLE_USER角色,/login.jsp也不例外,如果我们不为/login.jsp单独配置访问权限,会造成用户连登陆的权限都没有,这是不正确的。
2
login-page表示用户登陆时显示我们自定义的login.jsp。
这时我们访问系统显示的登陆页面将是我们上面创建的login.jsp。
3
authentication-failure-url表示用户登陆失败时,跳转到哪个页面。
当用户输入的登录名和密码不正确时,系统将再次跳转到/login.jsp,并添加一个error=true参数作为登陆失败的标示。
4
default-target-url表示登陆成功时,跳转到哪个页面。 [3]

4.3. 登陆页面中的参数配置

以下是我们创建的login.jsp页面的主要代码。
<div class="error ${param.error == true ? '' : 'hide'}">
  登陆失败<br>
  ${sessionScope['SPRING_SECURITY_LAST_EXCEPTION'].message}
</div>
<form action="${pageContext.request.contextPath}/j_spring_security_check" style="width:260px;text-align:center;">
  <fieldset>
    <legend>登陆</legend>
    用户: <input type="text" name="j_username" style="width:150px;" value="${sessionScope['SPRING_SECURITY_LAST_USERNAME']}"/><br />
    密码: <input type="password" name="j_password" style="width:150px;" /><br />
    <input type="checkbox" name="_spring_security_remember_me" />两周之内不必登陆<br />
    <input type="submit" value="登陆"/>
    <input type="reset" value="重置"/>
  </fieldset>
</form>
        
1
/j_spring_security_check,提交登陆信息的URL地址。
自定义form时,要把form的action设置为/j_spring_security_check。注意这里要使用绝对路径,避免登陆页面存放的页面可能带来的问题。 [4]
2
j_username,输入登陆名的参数名称。
3
j_password,输入密码的参数名称
4
_spring_security_remember_me,选择是否允许自动登录的参数名称。
可以直接把这个参数设置为一个checkbox,无需设置value,Spring Security会自行判断它是否被选中。
以上介绍了自定义页面上Spring Security所需的基本元素,这些参数名称都采用了Spring Security中默认的配置值,如果有特殊需要还可以通过配置文件进行修改。

4.4. 测试一下

经过以上配置,我们终于使用了一个自己创建的登陆页面替换了原来Spring Security默认提供的登录页面了。我们不仅仅是做个样子,而是实际配置了各个Spring Security所需的参数,真正将自定义登陆页面与Spring Security紧紧的整合在了一起。以下是使用自定义登陆页面实际运行时的截图。
进入登录页面
图 4.1. 进入登录页面

用户登陆失败
图 4.2. 用户登陆失败

实例见ch04。