Secure模块
提供了简单的验证功能,只要使用@With(Secure.class)标注在Controller上即可!
1.需要验证:
应用中99%的功能,都必须要登陆后才能访问,将这些功能所在的Controller都添加@With(Secure.class)。
当访问Controller中的任何方法时就会进行登录检查。【注:play在Secure类的checkAccess()上使用 @Before(unless={"login", "authenticate", "logout"}),将这3个方法排除了,不会拦截】
2.不需要验证:
如,登录页面,权限检查,登出动作,注册页面,这些都不需要验证。
play提供了一个登录页面,需要加入注册页面,那么就需要新建一个Controller,并且不能被Secure进行检查。该Controller不使用@With(Secure.class),注册页面就不会被拦截了。
login页面的路径显示问题
如果没有为secure模块指定路由,URL显示为:
http://localhost:9000/secure/login
如果为Secure模块指定了路由(Secure模块提供了一系列默认的路由配置):
#Import Secure routes
* / module:secure
则URL显示为:
http://localhost:9000/login
改造play的登陆页面,加入注册按钮
play secure:ov --login
修改app\views\Secure\login.html,添加注册按钮
- #{extends 'Secure/layout.html' /}
- <div id="login">
- <h1>&{'secure.title'}</h1>
- #{form @authenticate()}
- #{if flash.error}
- <p class="error">
- &{flash.error}
- </p>
- #{/if}
- #{if flash.success}
- <p class="success">
- &{flash.success}
- </p>
- #{/if}
- <p id="username-field">
- <label for="username">&{'secure.username'}</label>
- <input type="text" name="username" id="username" value="${flash.username}" />
- </p>
- <p id="password-field">
- <label for="password">&{'secure.password'}</label>
- <input type="password" name="password" id="password" value="" />
- </p>
- <p id="remember-field">
- <input type="checkbox" name="remember" id="remember" value="true" ${flash.remember ? 'checked="true"' : ''} />
- <label for="remember">&{'secure.remember'}</label>
- </p>
- <p id="signin-field">
- <input type="submit" id="signin" value="&{'secure.signin'}" />
- <!-- 加入注册按钮 -->
- <input type="button" id="reg" value="注册"/>
- </p>
- #{/form}
- </div>
复制Secure模块下的secure.css,重命名为login.css,放到public\stylesheets目录下
这样做的目的是,不对play内部的样式文件进行修改,而是拷贝单独一份进行使用
修改login.css,目的在于将2个按钮放在一行显示
- /*修改样式,将2个按钮放在一行*/
- #signin-field input {
- display: inline;
- margin-top: 10px;
- margin-left: 90px;
- }
- /*用户名框与密码框等长*/
- #username-field input {
- width: 150px;
- font-size: 13px;
- }
同样,将login.html所依赖的layout.html一起拷贝到项目中
play secure:ov --layout
修改引入的样式文件,指向刚才那个新的login.css,这样就脱离了对play内部的依赖。
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Login</title>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <!-- 使用修改后的样式文件 -->
- <link rel="stylesheet" type="text/css" media="screen" href="@{'/public/stylesheets/login.css'}" />
- </head>
- <body>
- #{doLayout /}
- </body>
- </html>
效果: