freemarker页面如何获取绝对路径basePath
1. freemarker获取系统相对路径方式
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);
}
});
};
即可获取带项目名的路径,但这路径是相对路径,浏览器输入http://localhost:8080/test-web/index.html访问,一切OK。
使用绝对路径方式
1. 问题来源
用域名直接访问系统,修改tomcat7配置文件使用http://localhost/index.html方式,即配置默认80端口和虚拟项目名称为空。
server.xml配置
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<Context path="" docBase="test-web" reloadable="true"/>
</Host>
修改后var base = document.getElementById("base").href;获取的base值是http://localhost/index.html但<base id="base" href="${base}">这里的href=""所以导致ajax的请求url : base + '/' + url,出现了问题。
2. 解决方案
增加spring拦截器,获取HttpServletRequest,拼装绝对路径放在request的attribute属性中,ftl文件中直接${basePath}取值就可以了,静态文件<link href="${basePath}/static/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">body中的隐藏表单<input type="hidden" id="base" value="${basePath}" />,js获取path也可以通过隐藏表单获取var base = $('#base').val();
拦截器代码
public class BasePathInterceptor extends HandlerInterceptorAdapter {
private static Logger logger = Logger.getLogger(BasePathInterceptor.class);
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String scheme = request.getScheme();
String serverName = request.getServerName();
int port = request.getServerPort();
String path = request.getContextPath();
String basePath = scheme + "://" + serverName + ":" + port + path;
logger.info(basePath);
request.setAttribute("basePath", basePath);
return true;
}
}
spring-mvc.xml中配置拦截器,拦截顺序至上而下
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.test.interceptor.BasePathInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/login.html"/>
<!-- <mvc:exclude-mapping path="/*/ajax/**"/> -->
<bean class="com.test.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
用上绝对路径之后,就会避免很多因为引用路径上带来的问题。
以上思路参考http://www.oschina.net/question/860595_140510的解决方案,通过继承freemarker视图解析类org.springframework.web.servlet.view.freemarker.FreeMarkerView,重写exposeHelpers方法,在spring里配置自己的freemarker的视图解析器,在模板中就可以通过${base}获取。
MyFreeMarkerView 代码
public class MyFreeMarkerView extends FreeMarkerView {
private static final String CONTEXT_PATH = "base";
@Override
protected void exposeHelpers(Map<String, Object> model,
HttpServletRequest request) throws Exception {
model.put(CONTEXT_PATH, request.getContextPath());
super.exposeHelpers(model, request);
}
}
spring-mvc.xml配置
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<!-- 自定义FreeMarkerView,用来定义项目的全局路径 -->
<property name="viewClass" value="com.kyt.utils.MyFreeMarkerView" />
</bean>
freemarker页面如何获取绝对路径basePath的更多相关文章
- springboot配置server相关配置&整合模板引擎Freemarker、thymeleaf&thymeleaf基本用法&thymeleaf 获取项目路径 contextPath 与取session中信息
1.Springboot配置server相关配置(包括默认tomcat的相关配置) 下面的配置也都是模板,需要的时候在application.properties配置即可 ############## ...
- nodejs之获取客户端真实的ip地址+动态页面中引用静态路径下的文件及图片等内容
1.nodejs获取客户端真实的IP地址: 在一般的管理网站中,尝尝会需要将用户的一些操作记录下来,并记住是哪个用户进行操作的,这时需要用户的ip地址,但是往往当这些应用部署在服务器上后,都使用了ng ...
- 关于在JSP页面中为什么一定要用${pageContext.request.contextPath}来获取项目路径,而不能用${request.contextPath}?
这里的疑问在于pageContext和request都是JSP中的内置对象之一,为什么不直接用${request.contextPath}来获取项目路径? 出现这种疑问,其实是将JSP的内置对象和EL ...
- request获取各种路径总结、页面跳转总结。
页面跳转总结 JSP中response.sendRedirect()与request.getRequestDispatcher().forward(request,response)这两个对象都可以使 ...
- SSH框架通过JFreeChart实现柱状图和获取项目路径
获取项目路径:String url= ServletActionContext.getRequest().getRealPath("/upload"); 一.直接生成的图片输出到j ...
- 从request获取各种路径总结 request.getRealPath("url")
转载:http://blog.csdn.net/piaoxuan1987/article/details/8541839 equest.getRealPath() 这个方法已经不推荐使用了,代替方法是 ...
- JAVA获取服务器路径的方法
1.在JSF环境中获取到ServletContext: 1 2 ServletContext sc = (ServletContext)FacesContext. getCurrent ...
- request 获取各种路径
从request获取各种路径总结 request.getRealPath("url"); // 虚拟目录映射为实际目录 request.getRealPath("./&q ...
- request.getContextPath获取绝对路径
request.getContextPath获取绝对路径 博客分类: 经验+注意 其他 request.getContextPath 项目需求:所有jsp页必须通过Action转发,不能直接在地址栏链 ...
随机推荐
- C语言头文件组织与包含原则
转自:http://www.cnblogs.com/clover-toeic/p/3728026.html 说明 本文假定读者已具备基本的C编译知识. 如非特殊说明,文中“源文件”指*.c文件,“头文 ...
- [译]:Orchard入门——媒体文件的添加与管理
原文链接:Adding and Managing Media Content 注:此文内容相对较老,实际操作指导性不强,仅适合做研究 当你利用富文本编辑器上传图片时(或者使用XML-RPC客户端,例如 ...
- DevExpress的GridControl的实时加载数据解决方案(取代分页)
http://blog.csdn.net/educast/article/details/4769457 evExpress是一套第三方控件 其中有类似DataGridView的控件 今天把针对Dev ...
- 【html+css】关于页面布局中遇到的问题记录
关于行内元素: 行内元素设置width无效, height无效(可以设置line-height), margin上下无效,padding上下无效,margin和padding可设置左右. text ...
- 【转】iOS学习之容易造成循环引用的三种场景
ARC已经出来很久了,自动释放内存的确很方便,但是并非绝对安全绝对不会产生内存泄露.导致iOS对象无法按预期释放的一个无形杀手是——循环引用.循环引用可以简单理解为A引用了B,而B又引用了A,双方都同 ...
- 洛谷 P1529 回家 Bessie Come Home Label:Dijkstra最短路 && 乱搞
题目描述 现在是晚餐时间,而母牛们在外面分散的牧场中. 农民约翰按响了电铃,所以她们开始向谷仓走去. 你的工作是要指出哪只母牛会最先到达谷仓(在给出的测试数据中,总会有且只有一只最快的母牛). 在挤奶 ...
- css样式表分类、选择器分类、css基础样式
1 . 样式表 Cascading Style Sheet css优势: 内容与表现分离 网页的表现统一,容易修改 丰富的样式,使网页布局更加灵活 减少网页代码量,增加网页的浏览速度,节省 ...
- linux install wineQQ
Linux上没有QQ太麻烦了,查了一下讲wineQQ安装上去了,亲测可以使用滴---就是版本低,安装步骤如下: 一.安装Wine 1.添加PPA sudo add-apt-repository ppa ...
- 有了门面,程序会更加体面!- pos软件基于三层架构 -09
续上篇) 大鸟说道:“实际上没有学过设计模式去理解三层架构会有失偏颇的,毕竟分层是更高一级别的模式,所谓的架构模式.不过在程序中,有意识的遵循设计原则,却也可以有效的做出好的设计.” ...
- React native 的弹出层(输入)效果
/*弹出层测试*/ import React,{Component} from 'react'; import { StyleSheet, View, Image, Text, TouchableOp ...