如何在spring中获取freemaker模板中的请求上下文

Aru*_*hny 28 spring freemarker spring-mvc

使用时如何在freemarker模板中获取请求上下文路径spring

我的观点解析器是这样的

    <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>
Run Code Online (Sandbox Code Playgroud)

我的视图解析器learn.common.web.view.FreemarkerViewResolver扩展了org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver

Aru*_*hny 36

在视图解析器中,您可以添加以下属性

<property name="requestContextAttribute" value="rc"/>
Run Code Online (Sandbox Code Playgroud)

然后在您的freemarker模板中,您可以获得请求上下文补丁

${rc.getContextPath()}
Run Code Online (Sandbox Code Playgroud)

  • 或者,您可以使用$ {rc.contextPath}来保存更多字符(至少在Spring 3中). (3认同)
  • `rc`参数的类型是什么? (2认同)

Mun*_*del 7

如果您的要求是在FTL视图中获取上下文路径,那么Spring提供了一个更好的替代方法 - 在视图中首先导入spring.ftl

<#import "/spring.ftl" as spring />
Run Code Online (Sandbox Code Playgroud)

然后使用宏@ spring.url作为您想要使上下文感知的URL -

<li id="history"><a href="<@spring.url '/rest/server/taskHistory'/>">History</a></li>
Run Code Online (Sandbox Code Playgroud)

这非常相似 -

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

其中rc在viewResolver中定义

基于XML的配置

<property name="requestContextAttribute" value="rc"/>
Run Code Online (Sandbox Code Playgroud)

或Spring Boot样式配置(aplication.yml)

spring.freemarker.request-context-attribute: rc
Run Code Online (Sandbox Code Playgroud)