java - 速度+ Spring

标签 java spring spring-mvc velocity

我正在尝试使用上述组件设置一个网络应用程序。除了集成 Spring 和 Velocity 工具的最后一个障碍,我已经跳过了所有障碍。我看到了this post今天早上,并更新了与提供的答案略有不同的答案。但是,一旦我尝试添加 ParameterTool像这样到我的模板之一:

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

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

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

最佳答案

The accepted answer 的略微修改版本来自 this question解决了这个问题。

您需要返回 ViewToolContext 而不是返回 ViewContext。您还需要准备工具箱并根据需要在 session /请求中设置它们:

您需要以您需要的任何方式初始化 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
       }
    }
}

关于java - 速度+ Spring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5033541/

相关文章:

java - Spring Data 仅使用 EntityGraph 抛出 EntityNotFoundException

java - 如何将按钮添加到 Canvas 而不让按钮调整大小?

Java、Dropbox : Get access token without copy pasting by user.

angular - 我们可以在 AOT 之后向 Angular 应用程序添加功能模块吗

java - 为什么传递给另一个 Activity 的 Serialized 对象为 null

java - 如何使用 JPA 从 1 自动生成 id?

java - 需要使用mockito测试apache poi excel

spring-mvc - 在spring mvc 3中,如何在返回ModelAndView的同时编写cookie?

json - 无法创建 [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter] 类型的内部 bean '(inner bean)'

java - 在一个匹配器中匹配多个属性