2011-02-17 84 views
4

我正在嘗試安裝一個帶有上述組件的webapp。我已經跳過了所有,但最後一個整合彈簧工具的障礙。今天早上我看到了this post,並用與提供的答案略有不同的答案對它進行了更新。但是,一旦我試圖在ParameterTool添加到我的模板之一,像這樣:Velocity + Spring

#foreach($key in $params.keySet()) 
    $key = $params.getValue($key) 
<br /> 
#end 

我收到NPE java.lang.UnsupportedOperationException:請求爲null。 ParameterTool必須先初始化!根據我讀過的內容,這意味着工具配置正確,只是它無法訪問請求。注意:我也接受了接受解決方案的錯誤。

有沒有人成功地使用Spring的這些工具?似乎這是一個已知的缺陷,因爲這是一個Open Jira Open Jira SPR-5514

回答

2

0123xx的0123xx的稍微修改版本可以解決此問題。

而不是返回一個ViewContext你需要返回一個ViewToolContext。您還需要準備工具箱,並根據適用情況在會話/請求中設置它們:

您將需要以您需要的方式初始化toolContext(查看我提供的答案here有關如何使用更新。API,因爲你將需要訪問ToolboxFactory

修改後的createVelocityContext方法現在需要事先準備的工具箱以下列方式創建ViewToolContext:

protected Context createVelocityContext(Map <String, Object> model, 
             HttpServletRequest request, 
             HttpServletRespsone response) 
             throws Exception { 

    initVelocityContext(); //Still keep toolContext static 
          //will need to also add this to 
          //the servletContext -- left as an exercise 
    prepareToolboxes(request, response); 
    Context context = 
     new ViewToolContext(getVelocityEngine(), request, 
           response, getServletContext()); 
    //Set model attrs to context 
    .... 
    return context; 
} 

private void prepareToolboxes(final HttpServletRequest request, 
           final HttpServletResponse response) { 
    String key = Toolbox.class.getName(); 
    if (factory.hasTools(Scope.REQUEST && request.getAttribute(key) == null) { 
     Toolbox requestTools = factory.createToolbox(Scope.REQUEST); 
     request.setAttribute(key, requestTools); 
    } 
    if (factory.hasTools(Scope.SESSION) { 
     HttpSession session = request.getSession(); 
     synchronized(factory) { 
      //Follow pattern from above 
     } 
    } 
} 
+0

事先警告,我有沒有完全測試所有的工具,但這確實解決了ParameterTool的問題。 – Scott