如何在freemarker模板中获取主机名?

时间:2012-03-28 11:44:01

标签: java spring freemarker

我将SpringMVC项目与Freemarker作为视图解析器。在一些模板中,我必须生成包括主机名在内的链接,但我无法得到它。 在JSP中我可以这样做:

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

我尝试使用“requestContextAttribute”,但requestContext.getContextPath()返回了没有主机名的路径。 我在哪里可以单独获得完整路径或主机名?

3 个答案:

答案 0 :(得分:1)

我们可以在JSTL中做到这一点。尝试在FreeMarker中进行调整:

${pageContext.request.serverName}

答案 1 :(得分:1)

了解Freemarker是故意设计为不了解其使用的上下文,使其更通用,这一点非常重要。这意味着与JSP不同,默认情况下它无法访问HttpServletRequest和Response对象。如果您希望它具有访问权限,您需要提供它。

我解决这个问题的方法是创建一个Servlet过滤器,将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()}

答案 2 :(得分:-1)

此代码应该在freemarker中使用:

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

但是对于freemarker,最好在java中获取服务器名称并将其作为字符串推送到模板中。