Velocity + Spring

半城伤御伤魂 提交于 2019-12-10 16:03:06

问题


I am attempting to setup a webapp with the above components. I've jumped all but the last hurdle which is integrating Spring & Velocity Tools. I saw this post this morning, and updated it with a slightly different answer than what was provided. However, once I attempted to add in ParameterTool to one of my templates like so:

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

I receive a NPE java.lang.UnsupportedOperationException: Request is null. ParameterTool must be initialized first! According to what I've read that means that the tooling was configured properly, just that it doesn't have access to the Request. Note: I receive the error with the accepted solution as well.

Has anyone successfully been able to use these tools with Spring? Seems that it's a known deficiency as there is an Open Jira for this Open Jira SPR-5514


回答1:


A slightly modified version of The accepted answer from this question resolves this issue.

Instead of returning a ViewContext you need to return a ViewToolContext. You will also need to prepare the toolboxes and set them on the session / request as applicable:

You will need to initialize the toolContext in whichever manner you need (look at my provided answer here on how to do this with the updated APIs, as you're going to need access to the ToolboxFactory.

The modified createVelocityContext method will now need to prepare the toolboxes prior to creating the ViewToolContext in the following manner:

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
       }
    }
}


来源:https://stackoverflow.com/questions/5033541/velocity-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!