首页 > 其他 > 详细

分享一个自己写的JFinal的BaseController

时间:2014-02-28 12:07:30      阅读:462      评论:0      收藏:0      [点我收藏+]

以前用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() {
		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.find("select * from " + getClazz().getSimpleName()
				+ " where id = " + 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);  

  }  

} 



权限之类的就需要你自己处理过滤了,过滤也非常方便的。

代码写得不好的地方请大家给予纠正。

@JFinal


分享一个自己写的JFinal的BaseController,布布扣,bubuko.com

分享一个自己写的JFinal的BaseController

原文:http://blog.csdn.net/hexin373/article/details/20040465

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!