当前位置:去问问>百科知识>java 怎么获取服务器webroot的路径

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

2024-08-19 06:26:08 编辑:zane 浏览量:546

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")调用全路路径了。

版权声明:文章由 去问问 整理收集,来源于互联网或者用户投稿,如有侵权,请联系我们,我们会立即处理。如转载请保留本文链接:https://www.qwenw.com/article/360371.html
热门文章