Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 688
Arun P Johny Avatar asked Aug 08 '09 15:08

Arun P Johny


People also ask

What is request context in spring boot?

public class RequestContext extends Object. Context holder for request-specific state, like current web application context, current locale, current theme, and potential binding errors. Provides easy access to localized messages and Errors instances.

How do I use FreeMarker template in spring boot?

Freemarker Template FilesSpring boot looks for the The template files under classpath:/templates/. And for the file extension, you should name the files with . ftlh suffix since Spring Boot 2.2. If you plan on changing the location or the file extension, you should use the following configurations.

What is spring FreeMarker?

FreeMarker is a Java based template engine from the Apache Software Foundation. Like other template engines, FreeMarker is designed to support HTML web pages in applications following the MVC pattern. This tutorial illustrates how to configure FreeMarker for use in Spring MVC as an alternative to JSP.


2 Answers

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()} 
like image 122
Arun P Johny Avatar answered Sep 20 '22 14:09

Arun P Johny


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 
like image 36
Munish Chandel Avatar answered Sep 18 '22 14:09

Munish Chandel