1. freemarker獲取系統相對路徑方式css
spring-mvc.xml 中配置html
<!-- 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" />是關鍵。web
ftl頁面中設置ajax
<#assign base=request.contextPath /> <!DOCTYPE html> <html lang="zh"> <head> <base id="base" href="${base}"> <title>首頁</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="${base}/static/bootstrap-3.3.4/css/bootstrap.min.css" rel="stylesheet"> <script src="${base}/static/bootstrap-3.3.4/js/bootstrap.min.js"></script> js文件中獲取path var base = document.getElementById("base").href; // 與後臺交互 _send = function(async, url, value, success, error) { $.ajax({ async : async, url : base + '/' + url, contentType : "application/x-www-form-urlencoded; charset=utf-8", data : value, dataType : 'json', type : 'post', success : function(data) { success(data); }, error : function(data) { error(data); } }); };
便可獲取帶項目名的路徑,但這路徑是相對路徑,瀏覽器輸入http://localhost:8080/test-web/index.html訪問,一切OK。spring
使用絕對路徑方式apache
1. 問題來源json
用域名直接訪問系統,修改tomcat7配置文件使用http://localhost/index.html方式,即配置默認80端口和虛擬項目名稱爲空。bootstrap
server.xml配置瀏覽器
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t "%r" %s %b" /> <Context path="" docBase="test-web" reloadable="true"/> </Host>
修改後var base = document.getElementById("base").href;獲取的base值是http://localhost/index.html但<base id="base" href="${base}">這裏的href=""因此致使ajax的請求url : base + '/' + url,出現了問題。spring-mvc
2. 解決方案
(1)增長spring攔截器,獲取HttpServletRequest,拼裝絕對路徑放在request的attribute屬性中,ftl文件中直接${basePath}取值就能夠了,靜態文件<link href="${basePath}/static/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">body中的隱藏表單<input type="hidden" id="base" value="${basePath}" />,js獲取path也能夠經過隱藏表單獲取var base = $('#base').val();
攔截器代碼
public class BasePathInterceptor extends HandlerInterceptorAdapter { private static Logger logger = Logger.getLogger(BasePathInterceptor.class); 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; } }
spring-mvc.xml中配置攔截器,攔截順序至上而下
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.test.interceptor.BasePathInterceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/login.html"/> <!-- <mvc:exclude-mapping path="/*/ajax/**"/> --> <bean class="com.test.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
用上絕對路徑以後,就會避免不少由於引用路徑上帶來的問題。
(2)經過繼承freemarker視圖解析類org.springframework.web.servlet.view.freemarker.FreeMarkerView,重寫exposeHelpers方法,在spring裏配置本身的freemarker的視圖解析器,在模板中就能夠經過${base}獲取。
MyFreeMarkerView 代碼
public class MyFreeMarkerView extends FreeMarkerView { private static final String CONTEXT_PATH = "base"; @Override protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception { model.put(CONTEXT_PATH, request.getContextPath()); super.exposeHelpers(model, request); } }
spring-mvc.xml配置
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <!-- 自定義FreeMarkerView,用來定義項目的全局路徑 --> <property name="viewClass" value="com.kyt.utils.MyFreeMarkerView" /> </bean>