How to use VelocityLayoutViewResolver in spring-webmvc with velocity

南笙酒味 提交于 2020-01-14 04:12:05

问题


    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
    <property name="prefix" value="" />
    <property name="suffix" value=".vm"></property>
    <property name="contentType" value="text/html;charset=UTF-8" />
    <property name="layoutUrl" value="layout/default.vm" />
</bean>

how the key word "layoutUrl" work in VelocityLayoutViewResolver?


回答1:


Its very common to have a dynamic web page divided into a layout part and a content part. The layout part might consist of a header, a footer, a sidebar, a navigation and so on. Elements meant to look more or less the same on every response, that is. But the content part differs, because that's where the action goes on, right?

Layout and content should be kept apart in different .vm files, so that the layout has to be designed (and changed) only once and the content part doesn't have to repeat anything.

The question is how to put those two parts together on each response. One approach is to parse the layout file in every content file. But as the layout usually wraps the content this very likely leads to more than one parsed layout file per content file.

A better way is to reverse that and to merge the content into the layout. This is way easier to handle. All you have to do is to declare a .vm file to work as the general layout file. In this file you put a var named $screen_content and magically the view you returned in your controller at a certain request is blended in at that spot.

Your layoutUrl property tells path and file name of your layout file relative to the resourceLoaderPath you have declared in this bean

<bean
    id="velocityConfig"
    class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
    <beans:property name="resourceLoaderPath" value="/WEB-INF/templates/" />
</bean>

Following your example...

<bean 
    id="viewResolver"
    class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
    ...
    <property name="layoutUrl" value="layout/default.vm" />
</bean>

...your layout file has to be /WEB-INF/templates/layout/default.vm



来源:https://stackoverflow.com/questions/34329147/how-to-use-velocitylayoutviewresolver-in-spring-webmvc-with-velocity

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