How to get the request context in a freemaker template in spring

大城市里の小女人 提交于 2019-11-30 13:38:33

问题


How to get the request context path in freemarker template when using with spring?

My view resolver is like this

    <bean id="freeMarkerViewResolver" class="learn.common.web.view.FreemarkerViewResolver">
        <property name="order" value="1" />
        <property name="viewClass"
        value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
        <property name="suffix" value=".ftl" />
        <property name="cache" value="false" />
    </bean>

My view resolver learn.common.web.view.FreemarkerViewResolver extends org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver


回答1:


In your view resolver you can add the following property

<property name="requestContextAttribute" value="rc"/>

Then in your freemarker template you can get the request context patch like

${rc.getContextPath()}



回答2:


If your requirement is to fetch the Context Path in your FTL view then Spring provides a better alternate - First import spring.ftl in your view

<#import "/spring.ftl" as spring />

Then use macro @spring.url for the URL which you want to make context aware -

<li id="history"><a href="<@spring.url '/rest/server/taskHistory'/>">History</a></li>

This is very much similar to -

<li id="history"><a href="${rc.getContextPath()}/rest/server/taskHistory">History</a></li>

Where rc is defined in viewResolver

XML based configuration

<property name="requestContextAttribute" value="rc"/>

or Spring Boot style configuration (aplication.yml)

spring.freemarker.request-context-attribute: rc


来源:https://stackoverflow.com/questions/1249205/how-to-get-the-request-context-in-a-freemaker-template-in-spring

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