JavaWeb中获取绝对路径的方法

JSP中获取绝对路径

在JSP中为了防止因目录变更找不到要加载的CSS,js文件和Servlet程序,有三种种方式可以获取绝对路径

1.<%=request.getContextPath()%>

代码实例:

//获取WebContent/js中的demo.js文件
<script type="text/javascript" src="<%=request.getContextPath() %>/js/demo.js"></script>

 2.${pageContext.request.contextPath}

代码实例:

//获取WebContent/js中的demo.js文件
<script type="text/javascript" src="${pageContext.request.contextPath}/js/demo.js"></script>

3.JSTL标签

代码示例

//访问DemoServlet
<c:url value="/DemoServlet">

Java程序中获取文件路径

比如读取根目录下的db.properties文件,代码如下:

Properties pro = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream("db.properties");
try {
            pro.load(in);
            this.driver = pro.getProperty("dataSource.driverClass");
            this.url = pro.getProperty("dataSource.jdbcUrl");
            this.username = pro.getProperty("dataSource.user");
            this.password = pro.getProperty("dataSource.password");
        }catch(Exception e) {
            e.printStackTrace();
        }

 

posted @ 2017-10-10 11:42  SoonZJ  阅读(341)  评论(0编辑  收藏  举报