Play Framework 完整实现一个APP(九)

时间:2023-03-08 17:23:42
Play Framework 完整实现一个APP(九)

添加增删改查操作

1.开启CRUD Module

/conf/application.conf 中添加

# Import the crud module
module.crud=${play.path}/modules/crud

  

/conf/routes 中添加

# Import CRUD routes
* /admin module:crud

  

需要重启Server,导入CRUD Module

2.添加控制器

/app/controllers

import play.*;
import play.mvc.*; public class Posts extends CRUD {
} public class Tags extends CRUD {
} public class Users extends CRUD {
} public class Comments extends CRUD {
}

可能会提示错误: CRUD 无法解析为类型 并且运行程序会提示错误

解决办法:

修改 conf/dependencies.yml

require:
- play
- play -> crud

  

运行Shell

> play dependencies

  

工程下会生成 modules/crud 文件,重新启动工程即可,但是编译还是会出错,可能是没有引用crud工程的原因

Play Framework 完整实现一个APP(九)

3.创建Controller

package controllers;

import models.User;

@CRUD.For(User.class)
public class AdminUsers extends CRUD { }

4.修改Model,添加验证

以User为例

public class User extends Model {
@Email
@Required
public String email; @Required
@Password
public String password; public String fullname;
public String isAdmin; public String toString() {
return email;
}
}

进入http://localhost:9000/admin/  选择add user进入 User Form进行测试

public class Post extends Model {
@Required
public String title; @Required
public Date postedAt; @Lob
@Required
@MaxSize(10000)
public String content; @Required
@ManyToOne
public User author; @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
public List<Comment> comments; @ManyToMany(cascade = CascadeType.PERSIST)
public Set<Tag> tags;
}
public class Tag extends Model implements Comparable<Tag> {

    @Required
public String name;
}
public class Comment extends Model {
@Required
public String author; @Required
public Date postedAt; @Lob
@Required
@MaxSize(10000)
public String content; @ManyToOne
@Required
public Post post;
}

5.页面上显示的Label名字是小写,与对应类的字段名一致,如果想显示大写,可以修改/conf/messages

title=Title
content=Content
postedAt=Posted at
author=Author
post=Related post
tags=Tags set
name=Common name
email=Email
password=Password
fullname=Full name
isAdmin=User is admin

  

Play Framework 完整实现一个APP(九)

。。