一。servlet中长用两种方式 获得路径
1. this.getServletContext.getRealPath(“”)获得的是webapps的路径(在tomcat中),getContextPath(")等同于this.getServletContext.getRealPath(“”)这种方法。在找打webspps的路径之后可以通过拼接找到其余路径.如:
String path=this.getServletContext.getRealPath("/WEB-INF/classes/db.properties/config.properties");
通过这种方式可找到所有所需路径。
2.另一种方式是获得该类所在的路径,如:“
Service.class.getClassloader().getResource("db.properties").getPath();这个直接从根目录开始查找,即classes目录下。注意Service.class.getClassloader().getResource("/db.properties").getPath()这种在前面加"/"是错误的写法,获取为null。
但是Service.class.getResource("/db.properties").getPath()是正确的写法,即从根目录下开始查找。
Service.class.getResource("db.properties").getPath()这样写则是从Service所在包下查找 。
下面这个网址给出了以上区别的解释:http://swiftlet.net/archives/868
http://www.cnblogs.com/yejg1212/p/3270152.html
二。我们经常看到在一些项目中,习惯性在路径前加一个“/”如:
(“/db.properties”)是指在当前路径下寻找此文件;
../ 是指在当前路径的上一级目录下寻找此文件;
../../ 是指在当前路径的上两级级目录下寻找此文件;
例:
String path=service.class.getClassloader().getResource("/db.properties").getPath();//默认从class文件所在文件 夹下加载
../db.properties 默认从class上一级目录,即WEB-INF目录
../../db.properties 默认从webroot目录开始读
三.在struts2中如果只想让其过滤.action的页面可以在web.xml中把/*改成*.action,注意千万不能把他改成/*.action,这是错误的,这样既是路径匹配又是正则匹配,就会报错。然后在struts.xml中<action>的name属性中不要加.action,系统会默认加上.action,只要在jsp页面中加上.action后缀即可。如<form action="login.action">而在struts.xml中<action>的name属性为:name="login"。
注:自己总结的,可能有错,如有错误,多多指教。
浙公网安备 33010602011771号