java如何得到项目的webRoot 路径?system.root

使用JAVA后台代码取得WEBROOT物理路径,可以有如下两种方式:
1、使用JSP Servlet取得WEB根路径可以用request.getContextPath(),相对路径request.getSession().getServletContext().getRealPath("/"),它们可以使用我们很容易取得根路径。

2、如果使用了spring, 在WEB-INF/web.xml中,创建一个webAppRootKey的param,指定一个值(默认为webapp.root)作为键值,然后通过Listener,或者Filter,或者Servlet执行String webAppRootKey = getServletContext().getRealPath("/"); 并将webAppRootKey对应的webapp.root分别作为Key,Value写到System Properties系统属性中。之后在程序中通过System.getProperty("webapp.root")来获得WebRoot的物理路径。
具体示例代码如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>csc2.root</param-value>
</context-param>
<listener>
<listener-class>test.ApplicationListener</listener-class>
</listener>
</web-app>

ApplicationListener.java
package test;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
public class ApplicationListener extends ContextLoaderListener {
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
String webAppRootKey = sce.getServletContext().getRealPath("/");
System.setProperty("csc2.root" , webAppRootKey);
String path =System.getProperty("csc2.root");
System.out.println("sssss:::"+path);
}
}

test.java
public class test {
public void remve(){
String path =System.getProperty("csc2.root");
System.out.println("result::::::::"+path);
}

}

index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="test.test" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
test t = new test();
t.remve();
%>
<html>
</html>
部署程序发布 启动TOMCAT 运行index.jsp 就可以调用JAVA中全局设置的物理路径了(说明这里的JSP 只是调用了TEST.JAVA 的remove方法,不做其他使用。原理解释,TOMCAT启动和读取WEB.XML 监听方式加载SPRING ApplicationListener继承SPRING ContextLoaderListener加载SPRING顺便吧全局路径赋值给csc2.root 描述,这样之后JAVA 代码中就可以使用System.getProperty("csc2.root")调用全路路径了。

https://zhidao.baidu.com/question/584970613.html

猜你喜欢

转载自blog.csdn.net/qb170217/article/details/81742080