freemarker頁面如何獲取絕對路徑basePath

spring-mvc.xml 中配置css

 1 <!-- FreeMarker視圖解析 如返回userinfo。。在這裏配置後綴名ftl和視圖解析器。。 -->
 2     <bean id="freemarkerViewResolver"
 3         class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
 4         <property name="viewClass"
 5             value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
 6         <property name="requestContextAttribute" value="rc" />
 7         <property name="suffix" value=".shtml" /> <!-- 後綴爲ftl,如:html、shtml等 -->
 8         <property name="contentType" value="text/html;charset=utf-8" />
 9         <property name="exposeRequestAttributes" value="true" />
10         <property name="exposeSessionAttributes" value="false" />
11         <property name="exposeSpringMacroHelpers" value="true" />
12         <property name="order" value="0" />
13     </bean>

其中<property name="requestContextAttribute" value="request" />是關鍵。html

頁面中取置web

 1 <#assign base=request.contextPath />
 2 <#--   <#assign base=${"request.contextPath"} /> 也能夠使用這種方式取值,但切記加雙引號  -->
 3 <!DOCTYPE html>
 4 <html lang="zh">
 5 <head>
 6     <base id="base" href="${base}"> <!-- 供js文件獲取路徑 var base = document.getElementById("base").href-->
 7     <title>首頁</title>
 8     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9     <link href="${base}/static/bootstrap-3.3.4/css/bootstrap.min.css" rel="stylesheet">
10     <script src="${base}/static/bootstrap-3.3.4/js/bootstrap.min.js"></script>
js法二:
<script> var base="${base}"</script>

js文件中獲取pathajax

 1 var base = document.getElementById("base").href;
 2 // 與後臺交互
 3 _send = function(async, url, value, success, error) {
 4     $.ajax({
 5         async : async,
 6         url : base + '/' + url,
 7         contentType : "application/x-www-form-urlencoded; charset=utf-8",
 8         data : value,
 9         dataType : 'json',
10         type : 'post',
11         success : function(data) {
12             success(data);
13         },
14         error : function(data) {
15             error(data);
16         }
17     });
18 };

 

原文出處:http://segmentfault.com/a/1190000002967105spring