当前位置:千优问>常见问答>java 怎么获取服务器webroot的路径

java 怎么获取服务器webroot的路径

2022-10-08 07:17:17 编辑:join 浏览量:636

java 怎么获取服务器webroot的路径

java 怎么获取服务器webroot的路径

使用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 webAppRootKey csc2.root test.ApplicationListener ApplicationListener.javapackage 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.javapublic 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(); %> 部署程序发布 启动TOMCAT 运行index.jsp 就可以调用JAVA中全局设置的物理路径了(说明这里的JSP 只是调用了TEST.JAVA 的remove方法,不做其他使用。原理解释,TOMCAT启动和读取WEB.XML 监听方式加载SPRING ApplicationListener继承SPRING ContextLoaderListener加载SPRING顺便吧全局路径赋值给csc2.root 描述,这样之后JAVA 代码中就可以使用System.getProperty("csc2.root")调用全路路径了。

标签:java,webroot,服务器