1. 程式人生 > >java web專案獲取src和WebContent目錄下的配置檔案

java web專案獲取src和WebContent目錄下的配置檔案

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目錄下讀取配置檔案的簡便方法。(不是從硬碟目錄下,有些方法很複雜),有解決方法的同學請貢獻出來。


參考:

附上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;
	}
	
}


相關推薦

java web專案獲取srcWebContent目錄配置檔案

1.首先上目錄結構: 2.部署到tomcat,在servlet中測試,測試程式碼: package test; import java.io.IOException; import java.io.InputStream; import java.util.Prope

Java web 專案讀取src或者tomcatclass目錄的xml檔案或者properties檔案

//生成一個檔案物件: File file = new File(getClass().getClassLoader().getResource("test.xml").getPath());

java web 專案 獲取客戶端 域賬戶計算機名

package com; import java.io.IOException; import java.net.InetAddress; import java.util.Enumeration; import javax.servlet.ServletException

Java Web專案,Android微信小程式的初始頁面配置

Java Web專案 我們在Eclipse裡開了Java Web專案之後,Run As Tomcat或者Apache伺服器,本地執行,如果直接用http://localhost:8080訪問專案,會發現瀏覽器會開啟一個預設的頁面。 這個頁面是在什麼地方配置的呢?

java web專案中daoservice前面為什麼要有介面呢??

介面提供了一個公用的方法提供方。 介面是用來規定子類的行為的。舉個例子吧 , 比如有個需求, 需要儲存客戶資訊, 有些客戶從網站來, 有些從手機客戶端來, 有些從後臺管理系統錄入, 假設不同來源的客戶有不同的處理業務流程, 這個時候我定義介面來提供一個儲存客戶的方法, 然後不同平臺實現我這個儲存客戶的介面,

java web專案獲取window/linux真實路徑

通用工具類 java web 專案 真實 路徑 獲取 windows linux 系統 : 這是在web專案中,獲取專案實際路徑的最佳方式,在windows和linux系統下均可正常使用: p

Java web專案的classpathclasspath*的區別,***的區別及如何查詢Java資原始檔路徑

這裡的專案都是Web專案才有classpath: web專案中的src路徑下的檔案在編譯後會放到WEB-INF/classess路徑下,預設的classpath路徑就是WEB-INF/classess路徑,直接放到WEB-INF下的話,是不在classpath下的。用ClassPathXmlApp

大型Java Web專案的架構部署調優問題

一位ID是jackson1225的網友在javaeye詢問了一個大型Web系統的架構和部署選型問題,希望能提高現有的基於Java的Web應用的服務能力。由於架構模式和部署調優一直是Java社群的熱門話題,這個問題引發了很多熱心網友的討論,其中一些意見對其它大型Web專案也有

java web專案獲取專案路徑

web專案相對路徑(不用考慮是否為windows伺服器或者Linux伺服器,如果採用絕對路徑對檔案進行操作,則要考慮linux的許可權問題): String savePath = request.ge

web專案部署以及放到ROOT目錄

     最近度過了一個國慶長假,好幾天都沒有寫部落格了!      釋出這篇案例也是希望能幫助到像我一樣的菜鳥o(* ̄︶ ̄*)o,百度上面的資料都不怎麼全。也沒有人說明注意事項。總是這篇說一點。那個人也說補一點,最後自己也是嘗試了好多次,各種坑踩過來了,以及一些優先順序和注意事項;      最近公

java 讀取src目錄配置檔案

1.使用java.util.Properties類 1.1 getResourceAsStream()有時候不一定讀的出來 Properties prop=new Properties(); InputStream in=new BufferedInput

為什麼我在eclipse中新建一個java web專案的時候多出了幾個檔案(Jax-Ws-Web Services 等等)我原先的項

如截圖所示,可能是因為選擇的檢視為JAVAEE所以就會出現下面的情況 檢視切換java沒估計原專案面搞web service 只需要開啟Java檢視即可 window選單--->Open

linux建立賬戶並自動生成主目錄目錄檔案 linux建立賬戶並自動生成主目錄目錄檔案

linux建立賬戶並自動生成主目錄和主目錄下的檔案   # useradd -d /home/test -m test; 然後給test設定密碼。 # passwd test;       1. useradd

通過adb命令獲取安卓私有目錄檔案

首先adb shell進入adb介面 命令su 獲取超級許可權 進入cd data/data/com.*(應用的系統目錄)/database/ 如果是獲取此資料夾下的.db檔案。需要把.db檔案設定成可讀寫 命令:chmod 777 test.db就把test.db設定為可

如何訪問android的asset目錄res目錄檔案

 在很多時候,我們需要訪問android中的資原始檔,這些資原始檔主要分為兩類,一種出於asset目錄下,稱為原生檔案,這類檔案在被打包成apk檔案時是不會進行壓縮的;另一類則是res下的檔案,這類檔案在打包成apk檔案時,會進行小記憶體優化的哦。    

IDEAmaven編譯打包Java專案成jar包但是resource配置檔案打包不成功

今天在IDEA下打包一個Java專案,準備打包成jar包直接執行,打包之後執行時候一直提示resource下資原始檔找不到,但我又確實配置了的,而且在IDEA上可以執行,但是打包成jar包之後就執行不了了。 後來百度,發現對於resource下檔案(prope

java resources目錄配置檔案的讀取操作封裝類

首先明確,java是編譯性語言,讀取應該都是針對編譯後的檔案. package com.xkygame.ssm.utils;/** * Created by Clarence on 2017/7/27. */import org.slf4j.Logger;import o

springmvc-WebContent目錄檔案訪問

首先清楚一個概念:對於/web-INF/及其子目錄, 是不允許直接的公共訪問,目的是保護這些程式碼 未經授權的訪問和窺視,更好的保護原始碼。而對於非/web-inf/及其子目錄,是允許直接訪問的。 springmvc的DispatcherServlet配置攔截URL為/,

Action 類 中訪問Webcontent目錄檔案

1、 action檔案要implements ServletRequestAware, 同時重寫setServletRequest 方法,在action類中定義 public HttpServletRequest request; 這樣一個成員變數。

maven工程中讀取resource目錄配置檔案

在maven工程中,我們會將配置檔案放到src/main/resources下面,例如我們需要確認resource 下的檔案編譯之後存放的位置。它編譯的路徑直接位於classes下面,這個路徑其實就是classPath的路徑,所以,在resources 根目錄下的配置檔案其實