java web项目获取src和WebContent目录下的配置文件
程序员文章站
2022-06-02 13:54:01
...
1.首先上目录结构:
2.部署到tomcat,在servlet中测试,测试代码:
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.ReadFile;
import utils.readFile.SysConfig;
/**
* Servlet implementation class testEvery
*/
@WebServlet("/testEvery")
public class testEveryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public testEveryServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* 访问url:http://localhost:8080/demoProj/testEveryServlet
*/
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
String path = request.getSession().getServletContext().getRealPath("/config/sysconfig.properties");
System.out.println("doGet读取到的/WEB-INF/config/sysconfig.properties:path:"+path);
String url = request.getSession().getServletContext().getRealPath("/WEB-INF/config/config.properties");
System.out.println("doGet读取到的/WEB-INF/config/config.properties:url:"+url);
/**
* 结果:
* doGet:path:D:\tomcat7\wtpwebapps\demoProj\config\sysconfig.properties
* doGet:url:D:\tomcat7\wtpwebapps\demoProj\WEB-INF\config\config.properties
*/
//只能获取src下面的
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/config/test.properties");
Properties prop = new Properties(); //map
prop.load(in);
String url1 = prop.getProperty("url");
System.out.println("获取到的url1:"+url1);//获取到的url1:www.baidu.com
//不可获取
InputStream in2 = this.getServletContext().getResourceAsStream("/WEB-INF/config.properties");
Properties prop2 = new Properties(); //map
prop.load(in2);
String url2 = prop2.getProperty("url");
System.out.println("获取到的url2:"+url2);//获取到的url2:null
//不可获取
InputStream in3 = this.getServletContext().getResourceAsStream("/webcontent.properties");
Properties prop3 = new Properties(); //map
prop.load(in3);
String url3 = prop3.getProperty("url");
System.out.println("获取到的url3:"+url3);//获取到的url3:null
//不可获取
InputStream in4 = this.getServletContext().getResourceAsStream("/config/wcc.properties");
Properties prop4 = new Properties(); //map
prop.load(in4);
String url4 = prop4.getProperty("url");
System.out.println("获取到的url4:"+url4);//获取到的url4:null
// 读取src下config包中的testJava.java
// InputStream in = ReadFile.class.getResourceAsStream("/config/testJava.java");//in为null
// byte[] a=new byte[100];
// in.read(a, 0, 900);
// System.out.println("读取src下config包中的testJava.java的输入流in的内容toString:"+in.toString());
// System.out.println("读取到的a:"+a);
String fileName3 = ReadFile.class.getResource("/config/test.properties").getFile();
System.out.println("读取src下config包中的test.properties:"+fileName3);
//输出:读取src下config包中的test.properties:/D:/tomcat7/wtpwebapps/demoProj/WEB-INF/classes/config/test.properties
// in.close();
// 读取src下 基名为myproperties的properties文件,获取其中name配置值
String value = ResourceBundle.getBundle("myproperties").getString("name");
System.out.println("获取到的myproperties.properties的值value:"+value);
//输出:获取到的myproperties.properties的值value:myname
// 读取src下myproperties.properties
InputStream in1 = ReadFile.class.getResourceAsStream("/myproperties.properties");
Properties properties = new Properties();
properties.load(in1);
String value2 = properties.getProperty("name"); // 获得name属性
System.out.println("获取到的myproperties.properties的值value2:"+value2);
//获取到的myproperties.properties的值value2:myname
//读取src下的
String sensitiveWordsServerPath1 = SysConfig.getSysParam("sensitiveWords_server_path1");
System.out.println("获取的sensitiveWordsServerPath1:"+sensitiveWordsServerPath1);
//获取的sensitiveWordsServerPath1:/datacms/htdocs/html/cctv/sensitiveWords/sws.xlsx
//读取src下的
String pp = prop("sensitiveWords_server_path1");
System.out.println("pp:"+pp);//pp:/datacms/htdocs/html/cctv/sensitiveWords/sws.xlsx
}
public String prop(String url){
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/sysconfig.properties");
Properties p = new Properties();
try {
p.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("p:"+p);
return p.getProperty(url);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String path = request.getSession().getServletContext().getRealPath("/config/sysconfig.properties");
System.out.println("doPost:path:"+path);
}
}
网上大量的读取配置文件的都是从src目录下,只有以下是从WebContent目录下读取的:
String path = request.getSession().getServletContext().getRealPath("/config/sysconfig.properties");
System.out.println("doGet读取到的/WEB-INF/config/sysconfig.properties:path:"+path);
String url = request.getSession().getServletContext().getRealPath("/WEB-INF/config/config.properties");
System.out.println("doGet读取到的/WEB-INF/config/config.properties:url:"+url);
/**
* 结果:
* doGet:path:D:\tomcat7\wtpwebapps\demoProj\config\sysconfig.properties
* doGet:url:D:\tomcat7\wtpwebapps\demoProj\WEB-INF\config\config.properties
*/
另:目前还没发现可以不启动tomcat,直接从当前项目WebContent目录下读取配置文件的简便方法。(不是从硬盘目录下,有些方法很复杂),有解决方法的同学请贡献出来。
参考:
http://blog.csdn.net/qhwc2009/article/details/45824815
http://blog.csdn.net/wjl_mgqs/article/details/7554741
http://www.cnblogs.com/duoting/p/4141044.html
http://blog.csdn.net/mar_ljh/article/details/39693979
附上SysConfig.java
package utils.readFile;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class SysConfig {
private static Logger logger = Logger.getLogger(SysConfig.class);
/**
* 将本类定义为singleton类
*/
private SysConfig(){
}
private static SysConfig mConfig= new SysConfig();
private Map<String,String> params = null;
private static String CONFIG_FILE="/config/sysconfig.properties";
private static String CONFIG_FILE_PATH = SysConfig.class.getClassLoader().getResource("").getPath().substring(1) + CONFIG_FILE;
public static String getSysParam(String param) {
return getAllParams().get(param);
}
public static Map<String,String> getAllParams() {
synchronized(mConfig){
if(mConfig.params==null){
mConfig.readConfig();
}
}
System.out.println("mConfig.params:"+mConfig.params);
return mConfig.params;
}
/**
* 重载配置文件
*/
public static void reloadConfig(JSONArray array) {
try{
Properties props = new Properties();
for(int i=0;i<array.size();i++){
JSONObject o = array.getJSONObject(i);
String key = o.keySet().iterator().next();
String value = o.getString(key);
mConfig.params.put(key, value);
props.setProperty(key, value);
}
String configFilePath = CONFIG_FILE_PATH;
if(!isLocal()){
configFilePath = "/" + CONFIG_FILE_PATH;
}
OutputStream out = new FileOutputStream(configFilePath);
props.store(out, "update");
}catch(Exception e){
logger.info("may error config");
}
}
private void readConfig() {
try {
Properties props = new Properties();
props.load(SysConfig.class.getResourceAsStream(CONFIG_FILE));
this.propertisToCache(props);
} catch (Exception e) {
logger.info("may error config");
}
}
/**
* 将配置写入内存
* @param properties
*/
private void propertisToCache(Properties props){
mConfig.params = new HashMap<String,String>();
Enumeration e = props.propertyNames();
while(e.hasMoreElements()) {
String key = (String)e.nextElement();
String value = props.getProperty(key);
params.put(key, value);
}
if(isLocal()) {
params.put("root_path", params.get("root_path_local"));
params.put("root_path_issue_temp", params.get("root_path_issue_temp_local"));
params.put("root_path_issue", params.get("root_path_issue_local"));
} else {
params.put("root_path", params.get("root_path_server"));
params.put("root_path_issue_temp", params.get("root_path_issue_temp_server"));
params.put("root_path_issue", params.get("root_path_issue_server"));
}
}
/**
* 判断系统类型
* @return:true为windows系统
*/
public static boolean isLocal() {
if (System.getProperty("os.name").contains("Windows")) {
return true;
}
logger.info("os is : " + System.getProperty("os.name"));
return false;
}
}
上一篇: JSP与Servlet文件上传和下载
下一篇: C++智能指针