Friday, 25 June 2010

Finding the request contextpath using Freemarker

I spent a good while Googling how to reference the request context path in Freemarker, and finally tracked down a solution on the Spring Source forum.

If a controller is intercepting requests at /app/blah/something, and your view loads CSS from static/css/, then your view will try and resolve the CSS at /app/blah/static/css/ -- which doesn't exist.

The solution is simple: in your views.xml, define the "requestContextAttribute" property, and assign it a value.

<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="requestContextAttribute" value="rc"></property>

Now in your templates you can use ${rc.contextPath} and your CSS will try and resolve to /app/static/css/ - perfect!

1 comment:

Windows 7 Key said...

Considerably, this post is really the sweetest on this notable topic. I harmonise with your conclusions and will thirstily look forward to your incoming updates. Saying thanks will not just be sufficient, for the phenomenal clarity in your writing. I will directly grab your rss feed to stay informed of any updates. Admirable work and much success in your business dealings!? Please excuse my poor English as it is not my f