场景
因为想把自己博客再写一个
Springboot+Layui的版本,以熟悉一下Springboot框架。在不改前端页面,依旧使用Enjoy模板引擎,所会就出现了如下场景
Enjoy
Spring Boot
MyBatis-Plus
Layui
MySQL
MySQL中字段是下划线,如:
article.create_time
实体中的字段是驼峰,如:Article.createTime
页面中使用Enjoy表达式输出
直接使用表名.字段名,如:#(article.create_time),会报如下错误
public field not found: "article.create_time" and public getter method not found: "article.getCreate_time()"
所以应当使用
#(article.createTime)
如果想在页面使用#(article.create_time)获取值,需要如下扩展
开始扩展
创建一个自定义FieldGetter
跟着JFinal波总的指导,创建一个CamelFieldGetter继承FieldGetter
以下代码是对
com.jfinal.template.expr.ast.FieldGetters.GetterMethodFieldGetter的修改
import com.jfinal.kit.StrKit;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.expr.ast.FieldGetter;
import com.jfinal.template.expr.ast.MethodKit;
/**
 * @author Max_Qiu
 */
public class CamelFieldGetter extends FieldGetter {
    protected java.lang.reflect.Method getterMethod;
    public CamelFieldGetter(java.lang.reflect.Method getterMethod) {
        this.getterMethod = getterMethod;
    }
    @Override
    public FieldGetter takeOver(Class<?> targetClass, String fieldName) {
        if (MethodKit.isForbiddenClass(targetClass)) {
            throw new RuntimeException("Forbidden class: " + targetClass.getName());
        }
        // 修改了下面这一行:先转驼峰,在将首字母大写,即可得到getCreateTime
        String getterName = "get" + StrKit.firstCharToUpperCase(StrKit.toCamelCase(fieldName));
        java.lang.reflect.Method[] methodArray = targetClass.getMethods();
        for (java.lang.reflect.Method method : methodArray) {
            if (method.getName().equals(getterName) && method.getParameterCount() == 0) {
                // if (MethodKit.isForbiddenMethod(getterName)) {
                // throw new RuntimeException("Forbidden method: " + getterName);
                // }
                return new CamelFieldGetter(method);
            }
        }
        return null;
    }
    @Override
    public Object get(Object target, String fieldName) throws Exception {
        return getterMethod.invoke(target, ExprList.NULL_OBJECT_ARRAY);
    }
    @Override
    public String toString() {
        return getterMethod.toString();
    }
}Engine中添加FieldGetter
在自定义的JFinalEnjoyConfig中,添加如下内容
Engine.addFieldGetterToLast(new CamelFieldGetter(null));
完毕!收工!
最后打一个自己博客的广告:原贴链接扩展FieldGetter使Enjoy在Springboot中支持下划线取值