看到有人问这方便的问题,把我当初学习JFinal时写的代码贴上来,希望有帮助.
package cn.flyinke.jke.beetl.common; import org.beetl.ext.jfinal3.JFinal3BeetlRenderFactory; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.config.Constants; import com.jfinal.core.Controller; import com.jfinal.core.JFinal; import com.jfinal.render.Render; import com.jfinal.render.RenderManager; public class BeetlRenderInterceptor implements Interceptor { private static final JFinal3BeetlRenderFactory rf = new JFinal3BeetlRenderFactory(); private static final Constants constants = JFinal.me().getConstants(); private static final RenderManager renderManager = RenderManager.me(); public BeetlRenderInterceptor() { rf.config(); System.out.println("beetl拦截器"); } @Override public void intercept(Invocation inv) { inv.invoke(); Render render = inv.getController().getRender(); Controller ctr = inv.getController(); if(render == null){ String view = inv.getMethodName()+constants.getViewExtension(); Render BeetlRender = rf.getRender(view); ctr.render(BeetlRender); }else{ String view = render.getView(); Render defaultRender = renderManager.getRenderFactory().getRender(view); //render 是否是默认 注意 有待改进 boolean flag = defaultRender.getClass().isAssignableFrom(render.getClass()); if(flag) { //替换 Render beetlRender = rf.getRender(view); ctr.render(beetlRender); } } } }
以上是beetl,同理可定义jsp,thymeleaf等拦截器,在需要的地方使用.
1:按 beetl 官方的配置集成到 jfinal 之中,然后 Controller.render(String) 方法就会自动使用 beetl
enjoy 引擎可以使用 renderTemplate 调用到,其它也类似:
renderJsp、renderFreemarker、renderVelocity
2:引入一个 BaseController ,在其中创建类似于 renderBeetl(String) 这样的方法实现功能,然后所有 Controller 继承这个 BaseController 即可