方式一:assign 变量
Spring配置如下:
<bean id="freemakerViewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<property name="suffix" value=".ftl"/>
<property name="contentType" value="text/html; charset=UTF-8" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="requestContextAttribute" value="request" />
<property name="order" value="1" />
<property name="cache" value="false"/>
bean>
编辑app.ftl:
<#assign path=request.contextPath >
<#if !path?ends_with("/") >
<#assign path=path+"/" >
#if>
<#assign basePath=path >
页面引入并引用
方式二:拦截器或者过滤器
在拦截器中手动获取contextPath,然后放入request属性中。
public class BaseInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String path = request.getContextPath();
String basePath = path;
request.setAttribute("basePath", basePath);
return true;
}
}
页面引用:
${basePath} 即可
方式三 : 通过自定义Freemarker的View
自定义FreeMarker的View类,并修改Spring配置文件。
public class MyFreeMarkerView extends FreeMarkerView {
private static final String CONTEXT_PATH = "basePath";
@Override
protected void exposeHelpers(Map model,
HttpServletRequest request) throws Exception {
String path = request.getContextPath();
String basePath = path;
model.put(CONTEXT_PATH, basePath);
super.exposeHelpers(model, request);
}
}
Spring配置文件修改如下:
"viewResolverFtl"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
"viewClass" value="com.myetak.basic.MyFreeMarkerView" />
//...
同样,页面使用${basePath}进行获取。
方式一修改如下:
<#assign basePath="192.168.88.133:8080"+path >
方式二 三修改如下:
public class BaseInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String scheme = request.getScheme();
String serverName = request.getServerName();
int port = request.getServerPort();
String path = request.getContextPath();
String basePath = scheme + "://" + serverName + ":" + port + path;
logger.info(basePath);
request.setAttribute("basePath", basePath);
return true;
}
}