jfinal急速demo的坑!!!很多人會看過我轉載的這篇文章,但是這個其實是有bug的!!!
很多人初學jfinal框架開發的時候可能都會看到類似下篇轉載來的文章,文章寫的小demo思路清晰,且十分詳盡,講道理,很感謝原創,雖然我也不知道誰是原創。。。但他的確給很多初嘗jfinal的朋友們提供了很好的思路,這點無可爭議。但是!他其實是有小bug的。。。
下面我們一起來看看這個jfinal的小demo是如何完成的吧!
JFinal 是基於 Java 語言的極速 WEB + ORM 開發框架,其核心設計目標是開發迅速、程式碼量少、學習簡單、功能強大、輕量級、易擴充套件、Restful。在擁有Java 語言所有優勢的同時再擁有 ruby、Python、PHP
JFinal 有如下主要特點:
MVC
架構,設計精巧,使用簡單
遵循 COC 原則,零配置,無 xml
獨創 Db + Record 模式,靈活便利
ActiveRecord 支援,使資料庫開發極致快速
自動載入修改後的 java 檔案,開發過程中無需重啟 web server
AOP 支援,攔截器配置靈活,功能強大
Plugin 體系結構,擴充套件性強
多檢視支援,支援 FreeMarker、JSP、Velocity
強大的 Validator 後端校驗功能
功能齊全,擁有 struts2 絕大部分核心功能
體積小僅 218K,且無第三方依賴
官方推薦用Eclipse IDE for Java EE Developers 做為開發環境,但我個人用慣了myecllipse+tomact
Eclipse IDE for java EE Developers 中
1、建立 Dynamic Web Project
2、修改 Default Output Folder,推薦輸入 WebRoot\WEB-INF\classes
特別注意:此處的 Default out folder 必須要與 WebRoot\WEB-INF\classes 目錄
完全一致才可以使用 JFinal 整合的 Jetty 來啟動專案。
3、修改 Content directory,推薦輸入 WebRoot
注 意 : 此 處 也 可 以 使 用 默 認 值 WebContent , 但 上 一 步 中 的
WebRoot\WEB-INF\classes 則需要改成 WebContent\WEB-INF\classes 才能對應上。
4、去官網下載最新的jar包(我這是JFinal-lib-1.4)
把jetty-server-8.1.8.jar 和JFinal-bin-1.4.jar放到專案 WEB-INF\lib下,jetty-server-8.1.8.jar是開發時使用的執行環境,用tomact和生產環境下就不需要了
5、新增到web.xml
<filter> <filter-name>jfinal</filter-name> <filter-class>com.jfinal.core.JFinalFilter</filter-class> <init-param> <param-name>configClass</param-name> <param-value>demo.DemoConfig</param-value> </init-param> </filter> <filter-mapping> <filter-name>jfinal</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
6、在專案 src 目錄下建立 demo 包,並在 demo 包下建立 DemoConfig 檔案, 內容如下:
package demo; import com.jfinal.config.*; public class DemoConfig extends JFinalConfig { public void configConstant(Constants me) { me.setDevMode(true); } public void configRoute(Routes me) { me.add("/hello", HelloController.class); } public void configPlugin(Plugins me) {} public void configInterceptor(Interceptors me) {} public void configHandler(Handlers me) {} }
注意:DemoConfig.java 檔案所在的包以及自身檔名必須與 web.xml 中的param-value 標籤內的配置相一致(在本例中該配置為 demo.DemoConfig)。
在 demo 包下建立 HelloController 類檔案, 內容如下:
package demo; import com.jfinal.core.Controller; public class HelloController extends Controller { public void index() { renderText("Hello JFinal World."); } }
6、右擊專案名選中com.jfinal.core.JFinal ok
7、瀏覽器輸入http://localhost/hello輸出內容為 Hello JFinal World 證明專案框架搭建完成。
注意:在 tomcat 下開發或執行專案時,需要先刪除 jetty-server-xxx.jar 這個包,否則會引起衝突。
(抄襲官網api,罪過罪過....)
jfinal真的挺簡單,迅速,強大的一個框架,沒有ssh的N多xml配置檔案,後面做個簡單的學生資訊管理,配合FreeMarker
上一節介紹了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 /> 性別: <<