七乐彩预测-上鼎狐网,玫瑰花的图片,匪夷所思造句
java web中解决路径问题:
java中使用的路径,分为两种:绝对路径和相对路径。归根结底,java本质上只能使用绝对路径来寻找资源。所有的相对路径寻找资源的方法,都不过是一些便利方法。不过是api在底层帮助我们构建了绝对路径,从而找到资源的!
在开发web方面的应用时, 经常需要获取 服务器中当前webroot的物理路径。
如果是servlet , action , controller, 或则filter , listener , 拦截器等相关类时, 我们只需要获得servletcontext, 然后通过servletcontext.getrealpath("/")来获取当前应用在服务器上的物理地址。
如果在类中取不到servletcontext时, 有两种方式可以做到:
1. 利用java的类加载机制 调用 xxx.class.getclassloader().getresource(""); 方法来获取到classpath , 然后处理获得webroot目录,这种方式只能是该class在webroot/web-inf/classes下才能生效, 如果该class被打包到一个jar文件中, 则该方法失效。这时就应该用下面一种方式。
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的物理路 径。
根据第二种的思路,我们还可以再扩展一下。不过对于在部署在一台服务器中的应用来说,若还不是你所需请再往下看。
下面是一些得到classpath和当前类的绝对路径的一些方法。你可使用其中的一些方法来得到你需要的资源的绝对路径:
1.
debitnoteaction.class.getresource("")
得到的是当前类filetest.class文件的uri目录。不包括自己!
如:
file:/d:/eclipse/springtest/webroot/web-inf/classes/
atacarnet/src/com/evi/modules/atacarnet/action/
2.
debitnoteaction.class.getresource("/")
得到的是当前的classpath的绝对uri路径。
如:
file:/d:/eclipse/springtest/webroot/web-inf/classes/
3.
thread.currentthread().getcontextclassloader().getresource("")
得到的也是当前classpath的绝对uri路径
如:
file:/d:/eclipse/springtest/webroot/web-inf/classes/
4.
debitnoteaction.class.getclassloader().getresource("")
或
classloader.getsystemresource("")
得到的也是当前classpath的绝对uri路径。
如:
file:/d:/eclipse/springtest/webroot/web-inf/classes/
5. 取得服务器相对路径
system.getproperty("user.dir")
例如:e:/apache-tomcat-5.5.16/apache-tomcat-5.5.16/bin
我推荐使用thread.currentthread().getcontextclassloader().getresource("")来得到当前的classpath的绝对路径的uri表示法
6. 取得项目中的绝对路径
一般用
request.getrealpath("/")
或
request.getrealpath("/config/")
但现在不提倡使用request.getrealpath("/")了,大家可试用servletcontext.getrealpath("/")方法得到web应用程序的根目录的绝对路径
要取得src的文件非常容易,因为src是默认的相对目录,比如你说要取得src下com目录的test.java文件,你只需要这样就够了
file f = new file(com/test.java);
但如果我要取得不在src目录或者webroot目录下的文件呢,而是要从src或者webroot同级的目录中取呢,比如说doc吧
我的硬方法是这样实现的:
string path = this.getservletcontext().getrealpath("/"); properties p = new properties(); p.load(new fileinputstream(new file(path.substring(0,(path.lastindexof("//webroot ") + 1)) + "doc/db.properties"))); system.out.println(p.getproperty("drivername"));
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论