Reputation: 9766
I have SpringMVC project with Freemarker as view resolver. In some templates I have to generate links including hostname, but I can't get it. In JSP I may to do like this:
`<% String hostName=request.getServerName();%>`
I tried to use "requestContextAttribute
", but requestContext.getContextPath()
returned path without hostname.
Where can I get full path or hostname separately?
Upvotes: 5
Views: 8087
Reputation: 1508
It's important to understand that Freemarker is intentionally designed to not have knowledge of the context in which it's used, to make it more generic. That means that unlike JSPs, it has no access to the HttpServletRequest and Response objects by default. If you want it to have access, you'll need to provide it.
The way I solved this was to create a Servlet Filter to add the HttpServletRequest object as a Request Attribute which Freemarker does have access to.
/**
* 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()
{
}
}
You'll need to define this in your web.xml in order for it to work:
<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>
Then, in my .ftl files, I can use the following:
${Request.RequestObject.getServerName()}
Upvotes: 1
Reputation: 4925
This code should work in freemarker:
<#assign hostname = request.getServerName() />
<a href="http://${hostname}/foo">bar</a>
But with freemarker it's better to get server name in java and push it into template as string.
Upvotes: 0
Reputation: 62603
We can do this in JSTL. Try adapting it in FreeMarker:
${pageContext.request.serverName}
Upvotes: 1