1.创建数据库JFinaldb,创建表books。然后插入一条记录。
create database JFinalDb;
use JFinalDb;
create table books(id int(10) primary key,name varchar(20),author varchar(20),price float(7,2));
insert into books(id,name,author,price)values('1','安徒生童话','安徒生','23.12');
2.打开eclipse,创建maven demo,我命名为haha。创建maven项目有困难的移步JFinal 文档、资料、学习、API,jfinal-undertow 下开发
3.修改pom.xml文件,插入依赖。
note:mysql和druid驱动的依赖(最后两个)你加入后如果报错,说明版本不对,需要你修改成你使用的版本。
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>jfinal-undertow</artifactId>
<version>2.8</version>
</dependency>
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>jfinal</artifactId>
<version>4.9.21</version>
</dependency>
<!--mysql驱动包-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
4.在java文件夹下创建如下三个包
config、controller、model
5.在config包里创建DbConfig,注意要继承他的父类JFinalConfig
6.同理,在controller包里创建BookController,继承父类Controller
7.在model包下创建类Book,继承Model
修改<M>为<Book>
8.在DbConfig中加入主方法:
public static void main(String[] args) {
UndertowServer.start(DbConfig.class, 80, true);
}
9.DbConfig类中还要修改这些方法(ps:以下这些方法是在你创建类的时候继承父类得来的,你只要找到对应的并修改就好啦!)
public void configConstant(Constants me) {
me.setDevMode(true); // 配置开发模式,true 值为开发模式
me.setInjectDependency(true);// 配置依赖注入
}
public void configRoute(Routes me) {
me.scan("controller."); // 路由扫描。"controller."表示扫描被限定的包名,扫描仅会在该包以及该包的子包下进行
}
public void configPlugin(Plugins me) {
String jdbcUrlString="jdbc:mysql://127.0.0.1:3306/JFnalDb";
DruidPlugin druidPlugin = new DruidPlugin(jdbcUrlString,"root","20001202");
ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(druidPlugin);
activeRecordPlugin.setDevMode(true);
activeRecordPlugin.setShowSql(true);
activeRecordPlugin.addMapping("user",Book.class);//完成映射
me.add(druidPlugin);
me.add(activeRecordPlugin);
}
上面这一步要注意到这些:
10.webapp文件夹下创建一个book文件夹,里面创建一个index.html
内容是:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书表</title>
</head>
<body>
<table>
<thead>
<h4>图书列表</h4>
</thead>
<tbody>
#for(book:books)
<tr>
<th>#(for.index)</th>
<th>#(book.id)</th>
<th>#(book.name)</th>
<th>#(book.author)</th>
<th>#(book.price)</th>
</tr>
#end
</tbody>
</table>
</body>
</html>
11. 修改BookController内容,进行查询操作
package controller;
import java.util.List;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import model.Book;
@Path("/book")
public class BookController extends Controller {
public static final Book dao= new Book().dao();
public void index() {
List<Record> bookList = Db.find("select * from books"); //进行查询
set("books",bookList);
render("index.html");
}
}
12.完成以上操作后,运行DbConfig。然后在浏览器输入: http://localhost/book
表中的记录已经显示出来了,查询操作完成。
13.接下来分别实现添加,删除,修改操作。注意每一个框要分别进行操作,操作完后就//掉,不然会报500错误。
注:这是用语句实现的,很土,不适合用户交互,可以看第二种方法⬇️。
法二
比较有难度,运用了生成器……完成后的页面如下(用了点bootstrap和css,设计比较简陋,可以自行完善):
1.在完成以上步骤的基础上,新建包 service,在里面创建一个名为 BookService的类。
2.在congfig包中加入Generator,并右键运行生成器 (生成器里数据库名和密码要改成你的)。
package config;
import javax.sql.DataSource;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.druid.DruidPlugin;
public class MyGenerator {
public static DataSource getDataSource() {
DruidPlugin dp = new DruidPlugin("jdbc:mysql://127.0.0.1:3306/JFinalDb?serverTimezone=UTC&characterEncoding=utf-8", "root", "20001202");
dp.start();
return dp.getDataSource();
}
public static void main(String[] args) {
//1 DataSource
//2 base model package name
String baseModelPackageName="model.base";
//3 base model dir
String baseModelOutputDir=PathKit.getWebRootPath()+"/../java/model/base";
//4 modelPackageName
String modelPackageName = "model";
//5 modelOutputDir
String modelOutputDir = baseModelOutputDir + "/..";
//
Generator gernerator= new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir);
gernerator.setDialect(new MysqlDialect());
// dao
gernerator.setGenerateDaoInModel(true);
gernerator.setGenerateDataDictionary(true);
gernerator.generate();
}
}
运行后右键刷新项目,会发现项目结构变成这样:
至于为什么要使用生成器?
3.Service层实现对dao的封装,进而实现对数据库增删改查的功能,BookService代码:
package service;
import java.util.Date;
import java.util.List;
import com.jfinal.kit.Ret;
import model.Books;
public class BookService {
public static final Books dao= new Books().dao();
//查找列表
public List<Books> getList(){
return dao.findAll();
}
public Books findById(Integer id) {
return dao.findById(id);
}
//删
public Ret deleteBookById(Integer id) {
Books book =dao.findById(id);
if(book==null) {
return Ret.fail("msg","删除失败");
}
boolean success=book.delete();
return success?Ret.ok("msg","删除成功"):Ret.fail("msg","删除失败");
}
//增
public Ret addBook(Books book) {
if(book==null) {
return Ret.fail("msg", "保存失败");
}
boolean success=book.save();
return success?Ret.ok("msg", "保存成功"):Ret.fail("msg","保存失败");
}
//改
public Ret updateBook(Books book) {
if(book==null||book.get("id")==null) {
return Ret.fail("msg","更新失败");
}
Books dbBook=dao.findById(book.getInt("id"));
if(dbBook==null) {
return Ret.fail("msg","更新失败");
}
boolean success=book.update();
return success?Ret.ok("msg","更新成功"):Ret.fail("msg","更新失败");
}
}
4.修改controller类
package controller;
import java.util.List;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import model.Books;
import service.BookService;
@Path("/book")
public class BookController extends Controller {
@Inject
BookService service;
public void index() {
// List<Record> bookList = Db.find("select * from books"); //进行查询
List<Books> bookList = service.getList();
set("books",bookList);
render("index.html");
}
public void delete() {
Integer idInteger=getInt(0);
service.deleteBookById(idInteger);
List<Books> bookList = service.getList();
set("books",bookList);
render("index.html");
}
public void add() {
//获取表单内容并填充到model里
Books book=getModel(Books.class,"book");//get para+new model with para
// System.out.println(book.toJson());
service.addBook(getModel(Books.class,"book"));
List<Books> bookList = service.getList();
set("books",bookList);
render("index.html");
// renderJson(service.addBook(getModel(Books.class,"book")));
}
public void edit() {
Books book=service.findById(getInt(0));
if(book==null) {
renderText("失败");
return;
}
set("book",book);
render("edit.html");
}
public void update() {
Books book=getModel(Books.class,"book");//get para+new model with para
service.updateBook(getModel(Books.class,"book"));
List<Books> bookList = service.getList();
set("books",bookList);
render("index.html");
}
}
5.webapp/book下新建 edit.html,这个页面是用于“改”操作
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h4>修改:</h4>
<form action="/book/update" method="post">
<div class="input-group mb-3">
<span class="input-group-text">id</span>
<input type="text" class="form-control" id="book.id" value="#(book.id??)" name="book.id">
</div>
<div class="input-group mb-3">
<span class="input-group-text">name</span>
<input type="text" class="form-control" id="book.name" value="#(book.name??)" name="book.name">
</div>
<div class="input-group mb-3">
<span class="input-group-text">author</span>
<input type="text" class="form-control" id="book.author" value="#(book.author??)" name="book.author">
</div>
<div class="input-group mb-3">
<span class="input-group-text">price</span>
<input type="text" class="form-control" id="book.price" value="#(book.price??)" name="book.price">
</div>
<button type="submit">修改</button>
</form>
</body>
</html>
6.修改webapp/book/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
<title>图书列表</title>
<style>
#books
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:100%;
border-collapse:collapse;
}
#books td, #books th
{
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
background-color:#e7e7e7;
}
#books th
{
font-size:1.1em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#FFFFFF;
}
button{
background-color: #e7e7e7;
border: none;
color: black;
padding: 10px 25px;
border-radius: 4px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.input-group{
width: 30%;
}
</style>
</head>
<body>
<table id="books">
<tbody>
<tr><th>序号</th><th>书号id</th><th>书名name</th><th>作者author</th><th>价格price</th><th>操作</th>
#for(book:books)
<tr>
<td>#(for.index)</td>
<td>#(book.id)</td>
<td>#(book.name)</td>
<td>#(book.author)</td>
<td>#(book.price)</td>
<td><a href="/book/delete/#(book.id)">删除</a> <a href="/book/edit/#(book.id)">修改</a></td>
</tr>
#end
</tbody>
<h4>图书列表:</h4>
</table>
<h4>添加图书:</h4>
<form action="/book/add" method="post">
<div class="input-group mb-3">
<span class="input-group-text">书名</span>
<input type="text" class="form-control" id="book.name" value="#(book.name??)" name="book.name">
</div>
<div class="input-group mb-3">
<span class="input-group-text">作者</span>
<input type="text" class="form-control" id="book.author" value="#(book.author??)" name="book.author">
</div>
<div class="input-group mb-3">
<span class="input-group-text">价格</span>
<input type="text" class="form-control" id="book.price" value="#(book.price??)" name="book.price">
</div>
<button type="submit">添加</button>
</form>
</body>
</html>
7.运行config类,浏览器输入http://localhost/book/,over。
note:页面里数据库相关的表字段名别粗心打错了。
THE END
有问题可以在评论区提出哦~