之前用struts的時候本身就寫了一個BaseAction
因此用JFinal的時候也寫了一個BaseControllerjava
但願對你們有所幫助,讓JFinal保持大道至簡this
import com.jfinal.core.Controller; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Page; import com.jfinal.plugin.activerecord.Record; public class BaseController extends Controller { private Class<?> clazz; // 對應的實體 public Class<?> getClazz() { return clazz; } public void setClazz(Class<?> clazz) { this.clazz = clazz; } /** * 通用分頁查找 */ public void getByPage() { Page<Record> list = Db.paginate(getParaToInt("pageNumber"), getParaToInt("pageSize"), "select *", "from " + getClazz().getSimpleName() + " order by id desc"); renderJson(list); } /** * 通用查找所有 */ public void getAll() { renderJson(Db.find("select * from " + getClazz().getSimpleName() + ";")); } /** * 通用根據id查找 */ public void getById() { renderJson(Db.findById(getClazz().getSimpleName(), getParaToInt("id"))); } /** * 通用新增 * * @throws Exception */ public void save() throws Exception { renderText(getModel( ((Model<?>) Class.forName(clazz.getName()).newInstance()) .getClass()).save() + ""); } /** * 通用修改 * * @throws Exception */ public void update() throws Exception { renderText(getModel( ((Model<?>) Class.forName(clazz.getName()).newInstance()) .getClass()).update() + ""); } /** * 通用刪除 * * @throws Exception */ public void delete() throws Exception { renderText(getModel( ((Model<?>) Class.forName(clazz.getName()).newInstance()) .getClass()).delete() + ""); } }
而後你的Controller只須要繼承BaseController.net
就自動有了BaseController的全部方法的,須要在構造方法裏把Mode的class映射進去code
Controller的代碼以下blog
public class CardController extends BaseController { public CardController() { setClazz(Card.class); } }
權限之類的就須要你本身處理過濾了,過濾也很是方便的。繼承
代碼寫得很差的地方請你們給予糾正。get
通過@JFinal的評論提示io
修改版的 BaseContorller 以下 :class