天天看點

JFinal開發8個常見問題

下面是8個最常見的問題總結。 

1.Can not create instance of class: demo.DemoConfig.

覺得應該是你的路徑有問題, 打開你項目的java build path面闆, 然後找到default output folder, 把這裡的輸出改為your_project/WebRoot/WEB-INF/classes。

2.jfinal自帶demo中如何在_layout.html加行<base href="${CONTEXT_PATH!}/"/>

按照如下步驟可解決問題:

在JFinalConfig中添加該ContextPathHandler,代碼如下

public void configHandler(Handlers me) {

    me.add(new ContextPathHandler());

}

在_layout.html 的 head标記中添加 base 标記,代碼如下

<base href="${CONTEXT_PATH}/" />

修改頁面中的連結标簽 a ,将最前面的 "/" 去掉,以下是要改的地方,可能有遺漏

比如:<link rel="stylesheet" type="text/css" href="static/framework/bootstrap/css/bootstrap.css" />

本質上來說context_path的問題僅與view有關,以上是JFinal提供的簡單處理方案 :)

3.如果更改JFinal的web.xml 攔截字尾名。

<filter-mapping>

      <filter-name>jfinal</filter-name>

      <url-pattern>/*</url-pattern>

  </filter-mapping>

 “/*”不能正确出力“.html”這種字尾的動态請求。

 參考資料:

 新增一個HtmSkipHandler檔案

 public class HtmSkipHandler extends Handler {  

    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {  

        int index = target.lastIndexOf(".htm");  

        if (index != -1)  

        target = target.substring(0, index);  

        nextHandler.handle(target, request, response, isHandled);  

    }  

再在JfinalConfig檔案增加

/**

     * 配置處理器

     */

    public void configHandler(Handlers me) {

        me.add(new HtmSkipHandler());

    }

4. URL中的參數,沒有在上下文中。

通路1個url,http://localhost/news/list.html?categoryId=2

Freemarker頁面${categoryId}竟然報錯。

必須在Controller的方法中,手動設定才行:

setAttr("categoryId",categoryId);

5.JFinal中restful攔截器如何實作。

jfinal中有restful攔截器,直接添加就是了。

 * 配置全局攔截器

 */

public void configInterceptor(Interceptors me) {

 me.add(new Restful());

URL:http://localhost/news/2

獲得參數:Integer id = getParaToInt(0);

但是,JFinal自帶的Restful攔截器是寫死的,比如"http://localhost/news/2"這個url隻能這麼寫,

響應方法隻能是show,而在SpringMVC中,可以很靈活,比如“/detail/{newsId}”,方法名随便取。

6.JFinal設定404和500等頁面。

public void configConstant(Constants me) {

me.setError404View(TEMPLATE_PATH+"/error/404.html");

me.setError500View(TEMPLATE_PATH+"/error/500.html");

7.JFinal統一異常處理。

public class ExceptionInterceptor implements Interceptor 

  public void intercept(ActionInvocation ai) {

Controller controller = ai.getController();

HttpServletRequest request = controller.getRequest();

try {

ai.invoke();

} catch (Exception e) {

me.add(new GlobalInterceptor());

me.add(new Restful());

me.add(new ExceptionInterceptor());

8.JFinal中配置Log4j。

源代碼src目錄下放置log4j.properties或log4j.xml,都行,xml格式也不需要額外配置listener之類的。