上个教程中,我们使用Spring Security框架的时候,路径被拦截之后跳转到的是Spring Security为我们准备好的一个登陆页面,虽然这个页面可以成功的实现登陆功能,但是这个简单的页面很多时候是不能满足我们的实际项目需求的,这就需要我们自定义登陆页面了,所以这次的教程就是学习如何自己定义登陆页面。
首先我们先创建一个login.html的文件,这个文件将做为我们的登陆页面,页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="login-box">
<h2>请输入账号和密码</h2>
<!--这里的"j_spring_security_check"是Spring Security的默认的登陆验证路径-->
<form name='loginForm'
action="j_spring_security_check" 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="submit" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
然后在spring-security.xml进行配置:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
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.2.xsd">
<http auto-config="true">
<!--访问前缀带有admin的路径都需要当前用户拥有ROLE_USER的权限-->
<intercept-url pattern="/admin**" access="ROLE_USER" />
<!--这里就是配置自定义登陆页面的标签 -->
<form-login
login-page="/login.html"
username-parameter="username"
password-parameter="password" />
</http>
<authentication-manager>
<authentication-provider>
<!--创建一个用户名为admin,登录密码为123456的账号,如果想要创建多个账号,可以在这里配置多个<user>标签-->
<user-service>
<user name="admin" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
这里要注意的是username-parameter和password-parameter需要和我们登陆页面中input标签的name属性相对应
配置好上面的内容之后,接下来我们访问admin.html,这时就会跳转到我们自己定义的login.html页面了