ja获取服务器路径

admin 129 2022-10-18

阿里云服务器优惠多,折扣错,惊喜多,请咨询:www.wqiis.com

本文目录一览:

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

?xml version="1.0" encoding="UTF-8"?

web-app version="2.4"

xmlns=""

xmlns:xsi=""

xsi:schemaLocation="

"

context-param

param-namewebAppRootKey/param-name

param-valuecsc2.root/param-value

/context-param

listener

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

java怎么取出linux服务器的文件路径

java可以获取当前项目的路径, Class.class.getClass().getResource("/").getPath()

这个是有请求的情况下,request.getSession().getServletContext().getRealPath("")

如何通过Java代码获取tomcat服务器的绝对路径

可以通过“ 类名.class.getResource("").getPath()”方法实现。

举例:”String path = XMLS.class.getResource("").getPath()“.

解释:以上语句就是获取到XMLS编译后的绝对路径(无法获取到java文件路径的,因为java运行的都是class文件)

ja获取服务器路径的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java获取服务器根路径、ja获取服务器路径的信息别忘了在维启网络进行查找喔。

上一篇:服务器哪个便宜
下一篇:服务器数据恢复一般要多久
相关文章

 发表评论

暂时没有评论,来抢沙发吧~