以前使用jsp開發的時候,可以通過request很輕松的獲取到根項目名,現在換到使用velocity渲染視圖,因為已經不依賴servlet,request等一些類的環境,而Web項目的根項目名又不是寫死的,需要動態獲取,這時候該怎么辦呢,試了網上說了很多種方式,總結一下心得.
第一種:(失敗)
在toolbox.xml里配置以下信息:
<toolbox scope="request">
<tool key="link" class="org.apache.velocity.tools.view.LinkTool"/>
</toolbox>然后在.vm里直接引用$link.contextPath
我依照這種方式配置完成,啟動瀏覽器打開項目的時候,頁面什么都刷不出來,按道理說如果它讀不到LinkTool的話,也應該在頁面中直接輸出$link.contextPath的呀,然后我在vm中去掉$link.contextPath,重新部署就可以刷出來頁面,我猜測可能是在讀toolbox.xml類的時候出了問題,然后在toolbox.xml中加入了一個自己寫的工具類測試:
<tool> <key>MyUtil</key> <class>com.ximalaya.shop.api.util.MyUtil</class> <scope>application</scope> </tool>
MyUtil類中有一個最簡單的靜態方法getMessage(),返回"test",然后我在vm中使用$MyUtil.message,測試.瀏覽器頁面成功返回test...看來不是讀取toolbox.xml的問題,debug了一下的確能進到LinkTool方法里,但是值總是為空,鼓搗了半天沒有解決,第一種方法,失敗!
第二種:(成功)
在spring配置文件的配viewResolver的地方添加一個參數:
<!--配置試圖解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="cache" value="false"/> <property name="prefix" value=""/> <property name="suffix" value=".vm"/> <property name="requestContextAttribute" value="rc"/> <property name="contentType" value="text/html;charset=utf-8"/> <property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/> <property name="exposeSpringMacroHelpers" value="true"/> <property name="exposeRequestAttributes" value="true"/> <property name="exposeSessionAttributes" value="true"/> <property name="allowSessionOverride" value="true"/> <property name="allowRequestOverride" value="true"/> </bean>
在vm文件中,直接使用$rc.contextPath可獲得項目名.
"requestContextAttribute" 把Spring的RequestContext對象暴露為變量rc。利用$rc.contextPath來獲取應用程序的contextPath(也 就是/MyUsers);利用${rc.getMessage("user.name")}讀取/WEB- INF/classes/messages.properties本地化信息。此對象對於那些不訪問serlvet請求的View技術(也就是 Velocity和FreeMarker模板)來說是必不可少的。