jfinal框架教程
jfinal框架教程
下面通過一個小例子了解jfinal的結構和特點
1、建數據庫(我用的是oracle數據庫,其他的相對也差不多)
-- Create table
create table CLASSES
(
classesid NUMBER not null,
classesname VARCHAR2(20),
classesaddress VARCHAR2(50)
);
-- Create table
create table STUDENT
(
studentid NUMBER not null,
studentname VARCHAR2(10),
studentage NUMBER,
studentsex VARCHAR2(2),
classesid NUMBER
);
alter table STUDENT
add constraint FK_CLASSESID foreign key (CLASSESID)
references CLASSES (CLASSESID);
新建項目,我用的myeclipse,先把jar包導入
2、實體類
Classes.java
package com.demo.model;
import com.jfinal.plugin.activerecord.Model;
public class Classes extends Model<Classes> {
public static final Classes dao = new Classes();
}
Student.java
package com.demo.model;
import com.jfinal.plugin.activerecord.Model;
public class Student extends Model<Student> {
public static final Student dao = new Student();
public Classes getClasses() {
return Classes.dao.findById(get("classesid"));
}
}
什麽這是實體類?沒錯!!~ ActiveRecord 是 jfinal 最核心的組成部分之一,通過 ActiveRecord 來操作數據庫,將極大地減少代碼量,極大地提升開發效率,配置在後面,我這裏用的是Model,Model 是 ActiveRecord 中最重要的組件之一,它充當 MVC 模式中的 Model部分。
以上代碼中的 User 通過繼承
Model,便立即擁有的眾多方便的操作數據庫的方法。在 User 中聲明的 dao 靜態對象是為了方便查詢操作而定義的,該對象並不是必須的。
基於ActiveRecord 的 Model 無需定義屬性, 無需定義 getter、 setter方法,無需 XML 配置,無需
Annotation 配置,極大降低了代碼量。Model常見方法見官方API。
JFinal還有 獨創 Db + Record 模式,Db 類及其配套的 Record 類, 提供了在 Model 類之外更為豐富的數據庫操作功能。使用 Db 與 Record 類時,無需對數據庫表進行映射,Record 相當於一個通用的 Model。Db常見方法見官方API。
3、DemoConfig.java
package com.demo.config;
import com.demo.controller.ClassesController;
import com.demo.controller.StudentController;
import com.demo.model.Classes;
import com.demo.model.Student;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
public class DemoConfig extends JFinalConfig {
@Override
public void configConstant(Constants me) {
}
@Override
public void configHandler(Handlers me) {
// TODO Auto-generated method stub
}
@Override
public void configInterceptor(Interceptors me) {
// TODO Auto-generated method stub
}
@Override
public void configPlugin(Plugins me) {
C3p0Plugin cp = new C3p0Plugin("jdbc:oracle:thin:@localhost:1521:orcl",
"test", "test");
// 配置Oracle驅動
cp.setDriverClass("oracle.jdbc.driver.OracleDriver");
me.add(cp);
ActiveRecordPlugin arp = new ActiveRecordPlugin(cp);
me.add(arp);
// 配置Oracle方言
arp.setDialect(new OracleDialect());
// 配置屬性名(字段名)大小寫不敏感容器工廠
arp.setContainerFactory(new CaseInsensitiveContainerFactory());
arp.addMapping("student", "studentid", Student.class);
arp.addMapping("classes", "classesid", Classes.class);
}
@Override
public void configRoute(Routes me) {
me.add("/", StudentController.class);
me.add("/student", StudentController.class);
me.add("/classes", ClassesController.class);
}
}
我這裏是oracle數據庫的配置,oracle有些特別的地方,如表列名會自動轉成大寫,配置個免大小寫的工廠,方便開發等。這裏要註意url,驅動,方言,在給個mysql數據庫的配置對比下
public class DemoConfig extends JFinalConfig {
public void configPlugin(Plugins me) {
C3p0Plugin cp = new C3p0Plugin("jdbc:mysql://localhost/db_name",
"userName", "password");
me.add(cp);
ActiveRecordPlugin arp = new ActiveRecordPlugin(cp);
me.add(arp);
arp.addMapping("user", User.class);
arp.addMapping("article", "article_id", Article.class);
}
}
4、StudentController.java
package com.demo.controller;
import java.util.List;
import com.demo.interceptor.StudentInterceptor;
import com.demo.model.Student;
import com.demo.validator.StudentValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
public class StudentController extends Controller {
@Before(StudentInterceptor.class)
public void index() {
List<Student> list = Student.dao.find("select * from student");
setAttr("studentList", list);
render("/index.html");
}
public void add() {
render("/add.html");
}
public void delete() {
// 獲取表單域名為studentID的值
// Student.dao.deleteById(getPara("studentID"));
// 獲取url請求中第一個值
Student.dao.deleteById(getParaToInt());
forwardAction("/student");
}
public void update() {
Student student = getModel(Student.class);
student.update();
forwardAction("/student");
}
public void get() {
Student student = Student.dao.findById(getParaToInt());
setAttr("student", student);
render("/index2.html");
}
@Before(StudentValidator.class)
public void save() {
Student student = getModel(Student.class);
student.set("studentid", "mysequence.nextval").save();
forwardAction("/student");
}
}
獲取studentid那裏有多種方法,這個要和前臺傳參寫法一致,Controller 提供了 getPara 系列方法,官網api裏很詳細
jfinal用的是原生態sql語句,簡單,方便,setAttr("studentList", list);把結果集放到request範圍裏,
jfinal也有直接獲取表單裏分裝成對象的方法 getModel(Student.class);就是,和struts2一樣,表單name對應上就可以了,非常方便
添加那裏對於oracle用序列維護studentid student.set("studentid", "mysequence.nextval").save(); jfinal有多種返回方式,也可以返回json數據,render 系列方法,官網api裏很詳細
5、interceptor和validator(可以不加)
StudentInterceptor.java
package com.demo.interceptor;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
public class StudentInterceptor implements Interceptor {
public void intercept(ActionInvocation ai) {
System.out.println("Before action invoking");
ai.invoke();
System.out.println("After action invoking");
}
}
StudentValidator.java
package com.demo.validator;
import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;
public class StudentValidator extends Validator {
//在校驗失敗時才會調用
@Override
protected void handleError(Controller controller) {
controller.keepPara("student.studentname");//將提交的值再傳回頁面以便保持原先輸入的值
controller.render("/add.html");
}
@Override
protected void validate(Controller controller) {
//驗證表單域name,返回信息key,返回信息value
validateRequiredString("student.studentname", "studentnameMsg",
"請輸入學生名稱!");
}
}
6、頁面
我這裏用的是FreeMarker模板引擎
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<a href="/student/add">添加</a>
<table border="1">
<tr>
<td>
姓名
</td>
<td>
年齡
</td>
<td>
性別
</td>
<td>
班級
</td>
<td>
操作
</td>
</tr>
<#list studentList as student>
<tr>
<td>
${student.studentname}
</td>
<td>
${student.studentage}
</td>
<td>
${student.studentsex}
</td>
<td>
${student.getClasses().classesname}
</td>
<td>
<a href="/student/delete/${student.studentid}">刪除</a>
<a href="/student/get/${student.studentid}">修改</a>
</td>
</tr>
</#list>
</table>
</body>
</html>
index2.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index2.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<form action="/student/update" method="post">
<input type="text" name="student.studentid" value="${student.studentid}"/>
姓名:
<input type="text" name="student.studentname" value="${student.studentname}"/>
<br />
年齡:
<input type="text" name="student.studentage" value="${student.studentage}"/>
<br />
性別:
<input type="text" name="student.studentsex" value="${student.studentsex}"/>
<br />
班級:
<input type="text" name="student.classesid" value="${student.classesid}" />
<br />
<input type="submit" value="保存" />
</form>
</body>
</html>
add.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>add.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<form action="/student/save" method="post">
姓名:
<input type="text" name="student.studentname" />${studentnameMsg!}${studentnameLMsg!}
<br />
年齡:
<input type="text" name="student.studentage" />
<br />
性別:
<input type="text" name="student.studentsex" />
<br />
班級:
<input type="text" name="student.classesid" />
<br />
<input type="submit" value="保存" />
</form>
</body>
</html>
完成! 瀏覽器輸入http://localhost/
jfinal框架教程