1、控制层代码
@Before(MyTemplateValidator.class)
public void update() {
Template template = getModelAndHandlingUltra(Template.class);
if (template.update()) {
renderJson(Ret.ok());
} else {
renderJson(Ret.fail());
}
}
public void delete() {
Template template = getModelAndHandlingUltra(Template.class);
template.delete();
redirect("/my/template");
}2、baseController层
/**
* 越权处理
* @param parentIdFieldName 父id字段名(标记数据所属关系)
* @param idFieldName (数据唯一标识,一般为主键字段名)
* @param tableName 要更新的数据表名
* @param idValue 数据唯一标识id值
*/
public void handlingUltra(String parentIdFieldName, String idFieldName, String tableName, Object idValue) {
Integer parentId = Db.queryInt("select "+parentIdFieldName+" from "+tableName+" where "+idFieldName+"=? limit 1", idValue);
if (parentId == null || parentId != getLoginAccountId()) {
throw new RuntimeException("SoJpt提示您: 请别尝试越权操作,否则后果自负!");
}
}
/**
* 遵守sojpt数据库设计规范, model表必须有唯一主键id/ID, 不推荐使用多主键
* @param model 待更新的model
* @param parentIdFieldName 父id字段名(标记数据所属关系)
* @return
*/
public void handlingUltra(Model<?> model, String parentIdFieldName) {
Table table = TableMapping.me().getTable(model.getClass());
String idFieldName = table.getPrimaryKey()[0];
handlingUltra(parentIdFieldName, idFieldName, table.getName(), model.get(idFieldName));
}
/**
* 遵守sojpt数据库设计规范, model表必须有唯一主键id/ID, 不推荐使用多主键
* 默认 parentIdFieldName 为自定义 "account_id"
* @param model 待更新的model
* @return
*/
public void handlingUltra(Model<?> model) {
Table table = TableMapping.me().getTable(model.getClass());
String idFieldName = table.getPrimaryKey()[0];
handlingUltra("account_id", idFieldName, table.getName(), model.get(idFieldName));
}
public <T> T getModelAndHandlingUltra(Class<T> modelClass) {
T model = getModel(modelClass);
handlingUltra((Model<?>) model);
return model;
}
public <T> T getModelAndHandlingUltra(Class<T> modelClass, String parentIdFieldName) {
T model = getModel(modelClass);
handlingUltra((Model<?>) model, parentIdFieldName);
return model;
}更多好玩的用法,请前往 sojpt.com 了解 sojpt 脚手架源码
对于绝大部分项目来说 BaseController 是标配。如果你的项目有登录功能,至少需要用来 User getLoginUser()、booloean isLogin()、getLoginUserId() 做这些事
感谢分享