jiggy
jiggy

Reputation: 3826

Get server name and scheme in freemarker with Spring MVC?

I'm using Freemarker as my view technology for a Spring MVC application. I need to find the server name and scheme and nothing I try seems to work. In JSP, there is an implicit request object that would have this info, but Freemarker doesn't seem to have an equivalent. I am exposing the Spring requestContext as rc, but rc.request is null.

Here is my view resolver config:

<bean id="freemarkerViewResolver"
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    <property name="cache" value="false" />
    <property name="suffix" value=".ftl" />
    <property name="order" value="1" />
    <property name="exposeRequestAttributes" value="true" />
    <property name="requestContextAttribute" value="rc" />
    <property name="exposeSpringMacroHelpers" value="true" />
</bean>


<bean id="freemarkerConfig"
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPaths">
        <list>
            <value>${freemarker.templatePath}</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8" />
</bean>

Upvotes: 0

Views: 2343

Answers (1)

Chaquotay inactive
Chaquotay inactive

Reputation: 2232

I think you can't access the Request via rc.request because RequestContext#getRequest is protected, i.e. not accessible from FreeMarker/reflection.

Disclaimer: I'm no Spring-MVC expert at all, so the following approach might be completely insane, but it should work!

You can expose the raw request with a custom FreeMarkerView and FreeMarkerViewResolver, e.g.

public class CustomFreeMarkerView extends FreeMarkerView {
    protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
        SimpleHash fmModel = super.buildTemplateModel(model, request, response);
        fmModel.put("RawRequest", request);
        return fmModel;
    }
}

public class CustomFreeMarkerViewResolver extends AbstractTemplateViewResolver {
    public CustomFreeMarkerViewResolver() {
        setViewClass(requiredViewClass());
    }   
    @Override
    protected Class requiredViewClass() {
        return CustomFreeMarkerView.class;
    } 
}

Then in your freemarkerViewResolver bean config you can use your custom view resolver class and access the raw request in your template via ${RawRequest}, e.g.

Scheme: ${RawRequest.scheme}
Server Name: ${RawRequest.serverName}

This approach worked for me with Spring Framework 3.0.5.

Upvotes: 3

Related Questions