操作 VelocityView 更改模板名称

Manipulating VelocityView to change the Template Name

我一直在开发企业规模的 Java 应用程序,它使用了 Apache Velocity.

这个应用程序基本上有很多供应商(网络所有者)并且在网络下可能有多个网站运行(供应商)。

前端使用Velocity View Engine渲染。

困境:

站点中的每个页面都有固定的 URL,但通过传递请求参数使页面具有唯一性,例如 site.html?vid=1&sid=20160109144.

现在,我一直在使用views.properties文件来确定模板名称,它有以下内容。

#Sitepage
site.(class)=com.sarvika.simplestack.velocity.config.SimpleStackVelocityView
site.url=site.vm

我正在使用自定义 ResourceLoader 加载模板。我的 ResourceLoader 期望模板名称必须是 vendorid/siteid/template.vm 形式,但由于我使用的是 views.properties 文件,它被限制为 template.vm.

目前的解决方案:

我试图通过扩展 Spring 框架的 org.springframework.web.servlet.view.velocity.VelocityView 来制作我的自定义 VelocityView class,到目前为止写了这个...

public class SimpleStackVelocityView extends VelocityView {
    
    @Override
    protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
        
        Long vendorid = RequestParameterResolver.getVendorID(request);
        Long siteid = RequestParameterResolver.getSiteID(request);
        
        if (siteid != null) {
            setUrl(siteid+"/"+getUrl());
        }
        
        if (vendorid != null) {
            setUrl(vendorid+"/"+getUrl());
        }
        
        super.exposeHelpers(model, request);
    }

}

我确实覆盖了这个方法,因为我需要访问 Servlet 请求,然后相应地更改模板的 URL。

麻烦:

第一次,它工作正常,URL 更改为 vendorid/siteid/template.vm,但对于后续页面重新加载,它更改为 vendorid/siteid/.../vendorid/siteid/template.vm

我可以进行哪些更改以获得所需的结果?

谢谢。

public class SimpleStackVelocityView extends VelocityView {

    private final static String SEPARATOR = "/";

    @Override
    protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {

        Long vendorid = RequestParameterResolver.getVendorID(request);
        Long siteid = RequestParameterResolver.getSiteID(request);

        /* This always gets the last part of the path.
         * So in this case it gets "template.vm"
         * as long as that is the last part of the path
        */
        String templateName = new File(getUrl()).getName();

        StringBuffer urlBuffer = new StringBuffer();

        if (vendorid != null) {
            urlBuffer.append(vendorid);
            urlBuffer.append(SEPARATOR);
        }

        if (siteid != null) {
            urlBuffer.append(siteid);
            urlBuffer.append(SEPARATOR);
        }

        urlBuffer.append(templateName);
        setUrl(urlBuffer.toString());

        super.exposeHelpers(model, request);
    }
}

如果 url 类似于 vendorid/siteid/.../vendorid/siteid/template.vm,则 templateName 将是 "template.vm"。如果 getUrl() 只是 returns "template.vm"(即首次加载时),templateName 仍将是 "template.vm".