以前用struts的时候自己就写了一个BaseAction
所以用JFinal的时候也写了一个BaseController希望对大家有所帮助,让JFinal保持大道至简
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() { Pagelist = 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
就自动有了BaseController的所有方法的,需要在构造方法里把Mode的class映射进去
Controller的代码如下
public class CardController extends BaseController { public CardController() { setClazz(Card.class); }}
权限之类的就需要你自己处理过滤了,过滤也非常方便的。
代码写得不好的地方请大家给予纠正。
经过的评论提示
修改版的 BaseContorller 如下 :