SSM项目中动态获取路径
EL表达式
通常/到达的路径是localhost:8080 缺失的是/manager-web/ 通常使用的EL表达式是这样的 ${ pageContext.request.contextPath }动态获取路径,为了简化人为设定值简化el表达式,先创建Listener,将contextPath值存入application域中,然后在页面上使用EL表达式从application域中获取。
先看效果
1.动态EL表达式
<link rel="stylesheet" href="${ pageContext.request.contextPath }bootstrap/css/bootstrap.min.css">
2.更改后完整的EL表达式
<link rel="stylesheet" href="${ applicationScope.APP_PATH }bootstrap/css/bootstrap.min.css">
3.更改后省略的EL表达式(applicationScope可以省略)
<link rel="stylesheet" href="${ APP_PATH }bootstrap/css/bootstrap.min.css">
思路:web应用启动创建AppPathLisetener对象,监听的是ServletContextListener,初始化就会调用contextInitialized方法执行代码,数据就会以APP_PATh为属性名存入到servletContext域里,页面就可以获取值。
首先我们在创建AppPathLisetener,并在相应的项目pom.xml中导入以赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
7.在Java项目中创建listener
public class AppPathLisetener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
//1获取ServletContext对象
ServletContext servletContext = sce.getServletContext();
//2获取ContextPath
String contextPath = servletContext.getContextPath();
//3将contextPath存入到ServletContext域中
servletContext.setAttribute("APP_PATh", contextPath);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
8.在web.xml中添加维护ContextPath值的监听器
<listener>
<listener-class>com.xxxx.xxx.listener.AppPathLisetener</listener-class>
</listener>
base标签
浏览器运行的时候把base标签里href=“”和如link标签里的href=“”拼接起来成为有效的,如果是/开头就不拼了,/代表的是http://localhost:8080/
<base href="http://${ pageContext.request.serverName }:${ pageContext.request.serverPort }${ pageContext.request.contextPath }/"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">