本文将使用Grails 写一个实现简单的登陆身份验证和权限拦截的Demo
如果没有搭建环境的,请移步到上篇博文 http://blog.csdn.net/hadues/article/details/52423067
- 创建 shadowApp Grails Web应用
grails create-app shadowApp
2.进入项目文件夹
cd shadowApp
3.创建用户实体类
grails create-domain-class User
Tips:
此命令执行成功后会生成两个文件
grails-app/domain/shadowapp/User.groovy
src/test/groovy/shadowapp/UserSpec.groovy
4.修改用户实体类
shadowApp\grails-app\domain\shadowapp\User.groovy
package shadowapp
class User {
/**
account: 登陆用户名
password:登陆密码
name:登陆用户昵称
*/
String account
String password
String name
/**
下面是对表字段进行约束
unique:true 表示唯一标识,相当于为表设置主键
password:true 表示密码不可为空
name() 表示用户昵称可以为空
*/
static constraints = {
account(unique:true)
password(password:true)
name()
}
}
5.为用户生成增删改查功能
grails generate-all shadowapp.User
6.修改用户控制器
package shadowapp
import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
@Transactional(readOnly = true)
class UserController {
...
/** 当执行login action时会转向login.gsp */
def login(){}
//身份验证
def authenticate(){
//查询数据库中账号和密码用于登陆比对
def user= User.findByAccountAndPassword(params.account,params.password)
if(user){//如果账号密码正确进入欢迎界面
session.user=user
flash.message="Hello ${user.name} !"
redirect(controller:"user",action:"welcome")
}else{//登陆失败,返回登陆界面
flash.message="Sorry, ${params.account},Please Try again !"
redirect(controller:"user",action:"login")
}
}
/**
注销登陆
*/
def logout(){
flash.mesage="Good Bye ${session.user.name}"
session.user=null
redirect(controller:"user",action:"login")
}
//登陆成功界面
def welcome(){
}
...
7.创建login.gsp
shadowApp\grails-app\views\user\login.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<title>Login</title>
</head>
<body>
<div class="body">
<h1>Login</h1>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<g:form action="authenticate" method="post" >
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td class="name">
<label for="login">Login:</label>
</td>
<td>
<input type="text" id="account" name="account"/>
</td>
</tr>
<tr class="prop">
<td class="name">
<label for="password">Password:</label>
</td>
<td>
<input type="password" id="password" name="password"/>
</td>
</tr>
</tbody>
</table>
</div>
<div class="buttons">
<span class="button">
<input class="save" type="submit" value="Login" />
</span>
</div>
</g:form>
</div>
</body>
</html>
8.创建登陆欢迎界面
shadowApp\grails-app\views\user\welcome.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<title>Login</title>
<style type="text/css">
#loginHeader {
float: right;
color: #000000;
}
</style>
</head>
<body>
<div id="header">
<div id="loginHeader">
<a href="/user/logout">注销</a>
</div>
</div>
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
</body>
</html>
9.运行程序
grails run-app