您的位置:首页 > 其它

分享一个自己写的JFinal的BaseController (1)

2014-02-27 11:24 323 查看
以前用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() {
[code]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()
+ "");
}

}[/code]

然后你的Controller只需要继承BaseController

就自动有了BaseController的所有方法的,需要在构造方法里把Mode的class映射进去

Controller的代码如下

public class CardController extends BaseController {

public CardController() {

setClazz(Card.class);

}

}


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

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

@JFinal
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: