Freemarker使用总结

 

 

spring mvc 中 Freemarker 获取项目根目录,方便HTML页面配置各种路径

 

在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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

其中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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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);
        }
    });
posted @   方东信  阅读(1296)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示