Freemarker获取项目根目录

"本文介绍了在SpringMVC框架中使用Freemarker模板引擎时,如何配置FreeMarkerViewResolver以暴露RequestContext,并在FTL页面及JS中通过`${request.contextPath}
摘要由CSDN通过智能技术生成
  1. 在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" />
    <!--关键:把Spring的RequestContext对象暴露为变量request利用${request.contextPath}来获取应用程序的contextPath-->
	<!--如果是集成了Springboot,在配置文件中,只需要设置spring.freemarker.request-context-attribute=request 即可-->
    <property name="requestContextAttribute" value="request" />
    <property name="cache" value="true" />
    <property name="order" value="0" />
</bean>
  1. ftl中的页面设置如下:
<!--freemarker配置获得项目根路径-->
<#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>
  1. 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);
	      }
});
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讓丄帝愛伱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值