freemarker页面如何获取jsp中的request.getContexPath

1.当controller的requestMapping()只有一级目录时(相对于项目名后多一级目录),该controller跳转的页面中引入js时的相对路径就是webapp

此时可以直接

<script src="static/bootstrap-3.3.4/js/bootstrap.min.js"></script>
路径static是webapp下的一级目录。
否则(如controller的requestMapping()中为(“xxx/xxx”)),需使用相对路径。

2. freemarker获取系统相对路径(webapp)方式

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>

其中<property name="requestContextAttribute" value="request" />是关键。

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文件中获取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);
        }
    });
};

猜你喜欢

转载自www.cnblogs.com/silver-aircraft/p/11996383.html
今日推荐