29

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

msp
  • 3,272
  • 7
  • 37
  • 49
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531

2 Answers2

37

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()}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 3
    Alternatively, you can use ${rc.contextPath} to save a few more characters (in Spring 3, at least). – Glenn Barnett Feb 01 '11 at 19:05
  • 2
    What is the type of the `rc` parameter? – EliuX Jul 17 '17 at 18:22
  • @EliuX it's of type `org.springframework.web.servlet.support.RequestContext` - so if you want to use it in a Freemarker Template, a `ftlvariable` directive like `<#-- @ftlvariable name="rc" type="org.springframework.web.servlet.support.RequestContext" --> ` helps your IDE regarding code completion. – Alexander Jan 16 '20 at 10:45
8

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
Munish Chandel
  • 3,572
  • 3
  • 24
  • 35
  • Or, if you use Spring Boot, you can use `springMacroRequestContext` variable: ``. Or set `spring.freemarker.request-context-attribute=rc` in app properties and then use `${rc.contextPath}` in any template. – Ruslan Stelmachenko Aug 16 '16 at 17:58