【问题标题】:How to get the request context in a freemaker template in springspring 如何在freemarker模板中获取请求上下文
【发布时间】:2010-11-17 23:09:13
【问题描述】:

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

我的视图解析器是这样的

    <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>

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

【问题讨论】:

    标签: spring spring-mvc freemarker


    【解决方案1】:

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

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

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

    ${rc.getContextPath()}
    

    【讨论】:

    • 另外,您可以使用 ${rc.contextPath} 保存更多字符(至少在 Spring 3 中)。
    • rc参数的类型是什么?
    • @EliuX 它的类型为 org.springframework.web.servlet.support.RequestContext - 因此,如果您想在 Freemarker 模板中使用它,ftlvariable 指令(如 &lt;#-- @ftlvariable name="rc" type="org.springframework.web.servlet.support.RequestContext" --&gt; )可以帮助您的 IDE 完成代码。
    【解决方案2】:

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

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

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

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

    这非常类似于 -

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

    其中rc在viewResolver中定义

    基于 XML 的配置

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

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

    spring.freemarker.request-context-attribute: rc
    

    【讨论】:

    • 或者,如果你使用Spring Boot,你可以使用springMacroRequestContext变量:&lt;link rel="stylesheet" href="${springMacroRequestContext.contextPath}/webjars/bootstrap/3.3.7/css/bootstrap.min.css"&gt;。或者在应用属性中设置spring.freemarker.request-context-attribute=rc,然后在任何模板中使用${rc.contextPath}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2017-10-14
    • 2010-09-18
    • 2012-04-12
    • 2019-02-07
    • 2012-05-04
    相关资源
    最近更新 更多