TimeFace-jFinalV3

RootController 继承 BasicController 在 index 方法中 确认restful接口;
POST---save保存、DELETE---delete删除、PUT----update更新、GET----show获取数据;

public void index() {
    String method = getRequest().getMethod();
    if (method.equals("POST")) {
        save();
        return;
    } else if (method.equals("DELETE")) {
        delete();
        return;
    } else if (method.equals("PUT")) {
        update();
        return;
    } else if (method.equals("GET")) {
        show();
        return;
    }
}

// JFinalV3中
com.jfinal.config.BasicController 继承自 jfinal的 Controller

public abstract class BasicController extends Controller {
    protected static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    public BasicController() {
    }

    protected void renderXml(String view) {
        this.render(new FreeMarkerXMLRender(view));
    }

    protected void renderError(String error) {
        this.renderJson(AjaxMessage.error(error));
    }

    protected void renderFailure(String failure) {
        this.renderJson(AjaxMessage.failure(failure));
    }

    protected void renderSuccess(String message) {
        this.renderJson(AjaxMessage.ok(message));
    }

    protected void renderSuccess() {
        this.renderJson(AjaxMessage.ok());
    }

    protected void renderError(String error, Exception e) {
        this.renderJson(AjaxMessage.error(error, e));
    }

    protected String renderTpl(String view) {
        Enumeration attrs = this.getAttrNames();
        HashMap root = Maps.newHashMap();

        while(attrs.hasMoreElements()) {
            String attrName = (String)attrs.nextElement();
            root.put(attrName, this.getAttr(attrName));
        }

        return FreemarkerKit.processString(view, root);
    }

    protected void todo() {
        this.renderJson(AjaxMessage.developing());
    }
}

配置文件AppConfig 继承自 JFinalConfig
com.jfinal.initalizer.AppConfig

public class AppConfig extends JFinalConfig {
    public static final String APPLICATION_PROP = "application.conf";
    private Routes routes;
    private Properties properties;
    private static final String MODEL_PACKAGE = "app.models";
    private static final String CONTROLLER_PACKAGE = "app.controllers";
    private static final String INTERCEPTORS_PACKAGE = "app.interceptors";
    private static final String BASE_VIEW_PATH = "/WEB-INF/views/";
    private static final String DEFAULT_DOMAIN = "http://127.0.0.1:8080/";
    private static String view_path;
    private static String domain;

    public AppConfig() {
    }

    public static String getBaseViewPath() {
        return view_path;
    }

    public static String getDomain() {
        return domain;
    }

    public void configConstant(Constants constants) {
        this.properties = this.loadPropertyFile("application.conf");
        constants.setDevMode(this.getPropertyToBoolean("dev.mode", false).booleanValue());
        constants.setLoggerFactory(new LogbackLoggerFactory());
        view_path = this.getProperty("view.path", "/WEB-INF/views/");
        constants.setBaseViewPath(view_path);
        domain = this.getProperty("domain", "http://127.0.0.1:8080/");
        String view_type = this.getProperty("view.type", "free_marker");
        ViewType viewType = ViewType.valueOf(view_type.toUpperCase());
        constants.setViewType(viewType);
        if(viewType == ViewType.FREE_MARKER) {
            Configuration view_404 = FreeMarkerRender.getConfiguration();
            view_404.setSharedVariable("block", new BlockDirective());
            view_404.setSharedVariable("extends", new ExtendsDirective());
            view_404.setSharedVariable("override", new OverrideDirective());
            view_404.setSharedVariable("super", new SuperDirective());
            view_404.setSharedVariable("prettyTime", new PrettyTimeDirective());
        }

        String view_4041 = this.getProperty("view.404");
        if(!Strings.isNullOrEmpty(view_4041)) {
            constants.setError404View(view_4041);
        }

        String view_500 = this.getProperty("view.500");
        if(!Strings.isNullOrEmpty(view_500)) {
            constants.setError500View(view_500);
        }

        try {
            int e = this.getPropertyToInt("thread.pool.size", Integer.valueOf(0)).intValue();
            if(e > 0) {
                ThreadPool.setPool(Executors.newFixedThreadPool(e));
            }

        } catch (Exception var7) {
            throw new ReflectException("thread pool size must be a number");
        }
    }

    public void configRoute(Routes routes) {
        this.routes = routes;
        routes.add(new AutoBindRoutes("app.controllers"));
    }

    public void configPlugin(Plugins plugins) {
        String db_url = this.getProperty("db.url");
        if(!Strings.isNullOrEmpty(db_url)) {
            DruidPlugin db1_url = new DruidPlugin(db_url, this.getProperty("db.username"), this.getProperty("db.password"));
            db1_url.addFilter(new StatFilter());
            WallFilter mongo_url = new WallFilter();
            mongo_url.setDbType("mysql");
            db1_url.addFilter(mongo_url);
            plugins.add(db1_url);
            AutoTableBindPlugin redis_host = new AutoTableBindPlugin(db1_url, SimpleNameStyles.LOWER_UNDERLINE, this.getProperty("db.models", "app.models"));
            redis_host.setDialect(new MysqlDialect());
            redis_host.setShowSql(this.getPropertyToBoolean("dev.mode", false).booleanValue());
            plugins.add(redis_host);
            if(this.getPropertyToBoolean("db.sqlinxml", false).booleanValue()) {
                plugins.add(new SqlInXmlPlugin());
            }
        }

        String db1_url1 = this.getProperty("db1.url");
        if(!Strings.isNullOrEmpty(db1_url1)) {
            DruidPlugin mongo_url1 = new DruidPlugin(db1_url1, this.getProperty("db1.username"), this.getProperty("db1.password"));
            mongo_url1.addFilter(new StatFilter());
            WallFilter redis_host1 = new WallFilter();
            redis_host1.setDbType("mysql");
            mongo_url1.addFilter(redis_host1);
            plugins.add(mongo_url1);
            SlaveAutoTableBindPlugin log_server = new SlaveAutoTableBindPlugin(mongo_url1, SimpleNameStyles.LOWER_UNDERLINE, this.getProperty("db1.models", "app.models"));
            log_server.setDialect(new MysqlDialect());
            log_server.setShowSql(this.getPropertyToBoolean("dev.mode", false).booleanValue());
            plugins.add(log_server);
            if(this.getPropertyToBoolean("db.sqlinxml", false).booleanValue()) {
                plugins.add(new SqlInXmlPlugin());
            }
        }

        if(this.getPropertyToBoolean("security", false).booleanValue()) {
            plugins.add(new ShiroPlugin(this.routes));
        }

        if(this.getPropertyToBoolean("cache", false).booleanValue()) {
            plugins.add(new EhCachePlugin());
        }

        if(this.getPropertyToBoolean("job", false).booleanValue()) {
            plugins.add(new QuartzPlugin(this.properties));
        }

        String mongo_url2 = this.getProperty("mongo.url");
        String redis_host2;
        int log_server1;
        if(!Strings.isNullOrEmpty(mongo_url2)) {
            redis_host2 = this.getProperty("mongo.host", "127.0.0.1");
            if(!Strings.isNullOrEmpty(redis_host2) || !Strings.isNullOrEmpty(mongo_url2)) {
                log_server1 = this.getPropertyToInt("mongo.port", Integer.valueOf(27017)).intValue();
                String alp = this.getProperty("mongo.db", "test");
                boolean moriph = this.getPropertyToBoolean("mongo.moriph", false).booleanValue();
                MongodbPlugin mongodb = new MongodbPlugin(redis_host2, log_server1, alp, moriph);
                plugins.add(mongodb);
            }
        }

        redis_host2 = this.getProperty("redis.host", "");
        if(!Strings.isNullOrEmpty(redis_host2)) {
            log_server1 = this.getPropertyToInt("redis.port", Integer.valueOf(6379)).intValue();
            JedisPlugin alp1 = new JedisPlugin(redis_host2, log_server1, 2000);
            plugins.add(alp1);
        }

        String log_server2 = this.getProperty("log.server", "");
        if(!Strings.isNullOrEmpty(log_server2)) {
            AkkaLogPlugin alp2 = new AkkaLogPlugin(log_server2);
            plugins.add(alp2);
        }

    }

    public void configInterceptor(Interceptors interceptors) {
        if(this.getPropertyToBoolean("dev.mode", false).booleanValue() && this.getPropertyToBoolean("db.sqlinxml", false).booleanValue()) {
            interceptors.add(new SqlInXmlInterceptor());
        }

        interceptors.add(new ContextInterceptor());
        (new AutoOnLoadInterceptor(interceptors, "app.interceptors")).load();
    }

    public void configHandler(Handlers handlers) {
        handlers.add(new SessionHandler());
        DruidStatViewHandler dvh = new DruidStatViewHandler("/admin/monitor", new IDruidStatViewAuth() {
            public boolean isPermitted(HttpServletRequest request) {
                return true;
            }
        });
        handlers.add(dvh);
        AddHeaderHandler ahh = new AddHeaderHandler();
        if(this.getPropertyToBoolean("allow.origin", false).booleanValue()) {
            ahh.addHeader("Access-Control-Allow-Origin", "*");
        }

        ahh.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, OPTIONS");
        ahh.addHeader("Access-Control-Allow-Headers", "tf-token,tf-uid,accept, content-type");
        handlers.add(ahh);
        UrlSkipHandler ush = new UrlSkipHandler(".*[/][A-Za-z0-9]+[.][w][s].*", true);
        handlers.add(ush);
    }
}

JFinalApplicationInitializer

public class JFinalApplicationInitializer
  implements ServletContainerInitializer
{
  public void onStartup(Set<Class<?>> classSet, ServletContext ctx)
    throws ServletException
  {
    URL url = Resources.getResource("application.conf");
    if (url == null) {
      throw new IllegalArgumentException("Parameter of file can not be blank");
    }
    InputSupplier<InputStream> inputSupplier = Resources.newInputStreamSupplier(url);
    try
    {
      Properties p = new Properties();
      p.load((InputStream)inputSupplier.getInput());
      boolean security = Boolean.getBoolean(p.getProperty("security", "false"));
      if (security)
      {
        ctx.addListener("org.apache.shiro.web.env.EnvironmentLoaderListener");
        ctx.addFilter("ShiroFilter", "org.apache.shiro.web.servlet.ShiroFilter")
          .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, new String[] { "/*" });
      }
      app_name = p.getProperty("app", "");
    }
    catch (IOException e)
    {
      String app_name;
      throw new IllegalArgumentException("Properties file can not be loading: " + url);
    }
    String app_name;
    FilterRegistration.Dynamic jfinalFilter = ctx.addFilter("jfinal@app", "com.jfinal.core.JFinalFilter");
    
    jfinalFilter.setInitParameter("configClass", "com.jfinal.initalizer.AppConfig");
    jfinalFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, new String[] { "/*" });
    
    jfinalFilter.setAsyncSupported(true);
    
    System.out.println("initializer " + app_name + " Application ok!");
  }
}

绑定路由:AutoBindRoutes
public class AutoBindRoutes extends Routes

public class AutoBindRoutes
  extends Routes
{
  private boolean autoScan = true;
  private List<Class<? extends Controller>> excludeClasses = Lists.newArrayList();
  private boolean includeAllJarsInLib;
  private List<String> includeJars = Lists.newArrayList();
  protected final Logger logger = Logger.getLogger(getClass());
  private String suffix = "Controller";
  private final String controller_package;
  
  public AutoBindRoutes(String controller_package)
  {
    this.controller_package = controller_package;
  }
  
  public AutoBindRoutes()
  {
    this.controller_package = "";
  }
  
  public AutoBindRoutes autoScan(boolean autoScan)
  {
    this.autoScan = autoScan;
    return this;
  }
  
  public AutoBindRoutes addExcludeClasses(Class<? extends Controller>... clazzes)
  {
    if (clazzes != null) {
      Collections.addAll(this.excludeClasses, clazzes);
    }
    return this;
  }
  
  public AutoBindRoutes addExcludeClasses(List<Class<? extends Controller>> clazzes)
  {
    this.excludeClasses.addAll(clazzes);
    return this;
  }
  
  public AutoBindRoutes addJars(String... jars)
  {
    if (jars != null) {
      Collections.addAll(this.includeJars, jars);
    }
    return this;
  }
  
  public void config()
  {
    ClassSearcher searcher = Strings.isNullOrEmpty(this.controller_package) ? ClassSearcher.of(Controller.class) : 
      ClassSearcher.of(Controller.class, this.controller_package);
    List<Class<? extends Controller>> controllerClasses = searcher
      .includeAllJarsInLib(this.includeAllJarsInLib).injars(this.includeJars).search();
    for (Class controller : controllerClasses) {
      if (!this.excludeClasses.contains(controller))
      {
        ControllerBind controllerBind = (ControllerBind)controller.getAnnotation(ControllerBind.class);
        if (controllerBind == null)
        {
          if (this.autoScan)
          {
            add(controllerKey(controller), controller);
            this.logger.debug("routes.add(" + controllerKey(controller) + ", " + controller.getName() + ")");
          }
        }
        else if (StringKit.isBlank(controllerBind.viewPath()))
        {
          add(controllerBind.controllerKey(), controller);
          this.logger.debug("routes.add(" + controllerBind.controllerKey() + ", " + controller.getName() + ")");
        }
        else
        {
          add(controllerBind.controllerKey(), controller, controllerBind.viewPath());
          this.logger.debug("routes.add(" + controllerBind.controllerKey() + ", " + controller + "," + 
            controllerBind.viewPath() + ")");
        }
      }
    }
  }
  
  private String controllerKey(Class<Controller> clazz)
  {
    Preconditions.checkArgument(clazz.getSimpleName().endsWith(this.suffix), 
      " does not has a @ControllerBind annotation and it's name is not end with " + this.suffix);
    String controllerKey = "/" + StringKit.firstCharToLowerCase(clazz.getSimpleName());
    controllerKey = controllerKey.substring(0, controllerKey.indexOf(this.suffix));
    return controllerKey;
  }
  
  public AutoBindRoutes includeAllJarsInLib(boolean includeAllJarsInLib)
  {
    this.includeAllJarsInLib = includeAllJarsInLib;
    return this;
  }
  
  public AutoBindRoutes suffix(String suffix)
  {
    this.suffix = suffix;
    return this;
  }
}

Run_Configurations.txt

Run Configurations... / Debug Configurations...

1: Main
project(required) ---> your_project_name
Main class(required) ---> com.jfinal.core.JFinal

2: Argument
Program arguments(optional) ---> WebRoot 80 / 5
VM arguments(optional) ---> -XX:PermSize=64M -XX:MaxPermSize=256M

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,594评论 18 139
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,849评论 0 6
  • Tutorials Videos Podcast Forums Store LOGIN / SIGN UPBECO...
    0x4d4746h阅读 609评论 0 1
  • 有人问泰戈尔三个问题:第一,世界上什么最容易?第二,世界上什么最难?第三,世界上什么最伟大?泰戈尔回答:指责别人最...
    勤录阅读 1,620评论 0 3
  • 周日的下午,大概是最转瞬即逝的好东西了。
    烟涩寒阅读 239评论 0 0