java – Velocity Spring

我正在尝试使用上述组件设置webapp.除了最后一个整合
Spring& amp;& amp; amp; amp; amp; amp;速度工具.我今天早上看了
this post,并且用一个与提供的答案略有不同的答案进行了更新.但是,一旦我尝试将
ParameterTool添加到我的一个模板中,就像这样:

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

我收到一个NPE java.lang.UnsupportedOperationException:Request为null.必须先初始化ParameterTool!根据我所读到的,这意味着工具配置正确,只是它无法访问请求.注意:我也收到了已接受解决方案的错误.

有没有人成功地使用这些工具与Spring?似乎这是一个已知的缺陷,因为这个Open Jira SPR-5514有一个Open Jira

最佳答案 从
this question稍微修改后的
The accepted answer版本可以解决此问题.

您需要返回ViewToolContext,而不是返回ViewContext.您还需要准备工具箱并在会话/请求中根据需要进行设置:

您将需要以您需要的任何方式初始化toolContext(请查看我提供的有关如何使用更新的API执行此操作的答案here,因为您将需要访问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
       }
    }
}
点赞