freemaker获取系统相对路径方式
-
如果是ssm项目,可以在spring-mvc.xml中配置
<!-- 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>
其中最重要的一行是获取 request 的路径信息,在前端页面通过 request 获取如下:
<property name="requestContextAttribute" value="request" />
现在已经获取好了当前路径,我们可以在 ftl 页面中获取,也可以在js文件中获取。
ftl 页面:
<#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 文件:
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);
}
});
};
-
如果是SpringBoot项目,可以在application.properties文件中配置
spring.freemarker.request-context-attribute=request
在 ftl 页面中直接通过 ${request.contextPath} 获取当前路径:
<link rel="stylesheet" href="${request.contextPath}/layui/css/layui.css"/>