SpringBoot 部署到 tomcat 上出现静态资源路径缺少项目名问题

本文介绍如何在SSM和SpringBoot项目中使用Freemarker获取系统相对路径的方法。通过配置视图解析器并利用request对象,可在前端页面及JS文件中获取到正确的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"/>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值