在SpringMVC架構中使用Freemarker試圖時,要擷取根路徑的方式如下:
<!-- FreeMarker視圖解析 如傳回userinfo。。在這裡配置字尾名ftl和視圖解析器。。 -->
<bean id="viewResolverFtl"
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="cache" value="true" />
<property name="order" value="0" />
</bean>
其中property name=”requestContextAttribute” value=”request”是關鍵。
意思是把Spring的RequestContext對象暴露為變量request
利用${request.contextPath}來擷取應用程式的contextPath
如果是內建了Springboot,在配置檔案中,隻需要設定
spring.freemarker.request-context-attribute=request 即可
ftl中的頁面設定如下:
<#assign ctx=request.contextPath />
<!DOCTYPE html>
<html lang="zh">
<head>
<base id="ctx" href="${ctx}">
<title>首頁</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="${ctx}/static/bootstrap-3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="${ctx}/static/bootstrap-3.3.4/js/bootstrap.min.js"></script>
js檔案中擷取path
var base = document.getElementById("ctx").href;
// 與背景互動
$.ajax({
url : base + '/' + url,
data : value,
dataType : 'json',
type : 'post',
success : function(data) {
success(data);
},
error : function(data) {
error(data);
}
});