How to get hostname in freemarker template?

I have a SpringMVC project with Freemarker as a view resolver. In some templates, I have to generate links, including the host name, but I cannot get it. In JSP, I can do the following:

`<% String hostName=request.getServerName();%>`

I tried using " requestContextAttribute", but requestContext.getContextPath()returned the path without a hostname. Where can I get the full path or hostname separately?

+5
source share
3 answers

We can do this in JSTL. Try to adapt it in FreeMarker:

${pageContext.request.serverName}
+1
source

, Freemarker , , , . , JSP, HttpServletRequest Response . , , .

, , HttpServletRequest , Freemarker.

/**
 * This simple filter adds the HttpServletRequest object to the Request Attributes with the key "RequestObject" 
 * so that it can be referenced from Freemarker.
 */
public class RequestObjectAttributeFilter implements Filter
{

    /**
     * 
     */
    public void init(FilterConfig paramFilterConfig) throws ServletException
    {

    }

    public void doFilter(ServletRequest req,
        ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException
    {
        req.setAttribute("RequestObject", req);

        filterChain.doFilter(req, res);
    }

    public void destroy()
    {

    }

}

web.xml, :

<filter>
     <filter-name>RequestObjectAttributeFilter</filter-name>
     <filter-class>com.foo.filter.RequestObjectAttributeFilter</filter-class>    
</filter>

<filter-mapping>
     <filter-name>RequestObjectAttributeFilter</filter-name>
     <url-pattern>/*</url-pattern>
</filter-mapping>

.ftl :

${Request.RequestObject.getServerName()}
+1

This code should work in freemarker:

<#assign hostname = request.getServerName() />
<a href="http://${hostname}/foo">bar</a>

But with freemarker it is better to get the server name in java and paste it into the template as a string.

-1
source

All Articles