web项目获取资源文件

2019年11月17日 阅读数:204
这篇文章主要向大家介绍web项目获取资源文件,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

java web项目获取src和WebContent目录下的配置文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处连接和本声明。
本文连接: https://blog.csdn.net/superit401/article/details/78206877

1.首先上目录结构:javascript



2.部署到tomcat,在servlet中测试,测试代码:php


        
        
  1. package test;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.Properties;
  5. import java.util.ResourceBundle;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.WebServlet;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import utils.ReadFile;
  12. import utils.readFile.SysConfig;
  13. /**
  14. * Servlet implementation class testEvery
  15. */
  16. @ WebServlet( "/testEvery")
  17. public class testEveryServlet extends HttpServlet {
  18. private static final long serialVersionUID = 1L;
  19. /**
  20. * @see HttpServlet#HttpServlet()
  21. */
  22. public testEveryServlet() {
  23. super();
  24. // TODO Auto-generated constructor stub
  25. }
  26. /**
  27. * 访问url:http://localhost:8080/demoProj/testEveryServlet
  28. */
  29. /**
  30. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  31. */
  32. protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  33. // TODO Auto-generated method stub
  34. response.getWriter().append( "Served at: ").append(request.getContextPath());
  35. String path = request.getSession().getServletContext().getRealPath( "/config/sysconfig.properties");
  36. System.out. println( "doGet读取到的/WEB-INF/config/sysconfig.properties:path:"+path);
  37. String url = request.getSession().getServletContext().getRealPath( "/WEB-INF/config/config.properties");
  38. System.out. println( "doGet读取到的/WEB-INF/config/config.properties:url:"+url);
  39. /**
  40. * 结果:
  41. * doGet:path:D:\tomcat7\wtpwebapps\demoProj\config\sysconfig.properties
  42. * doGet:url:D:\tomcat7\wtpwebapps\demoProj\WEB-INF\config\config.properties
  43. */
  44. //只能获取src下面的
  45. InputStream in = this.getServletContext().getResourceAsStream( "/WEB-INF/classes/config/test.properties");
  46. Properties prop = new Properties(); //map
  47. prop.load( in);
  48. String url1 = prop.getProperty( "url");
  49. System.out. println( "获取到的url1:"+url1); //获取到的url1:www.baidu.com
  50. //不可获取
  51. InputStream in2 = this.getServletContext().getResourceAsStream( "/WEB-INF/config.properties");
  52. Properties prop2 = new Properties(); //map
  53. prop.load(in2);
  54. String url2 = prop2.getProperty( "url");
  55. System.out. println( "获取到的url2:"+url2); //获取到的url2:null
  56. //不可获取
  57. InputStream in3 = this.getServletContext().getResourceAsStream( "/webcontent.properties");
  58. Properties prop3 = new Properties(); //map
  59. prop.load(in3);
  60. String url3 = prop3.getProperty( "url");
  61. System.out. println( "获取到的url3:"+url3); //获取到的url3:null
  62. //不可获取
  63. InputStream in4 = this.getServletContext().getResourceAsStream( "/config/wcc.properties");
  64. Properties prop4 = new Properties(); //map
  65. prop.load(in4);
  66. String url4 = prop4.getProperty( "url");
  67. System.out. println( "获取到的url4:"+url4); //获取到的url4:null
  68. // 读取src下config包中的testJava.java
  69. // InputStream in = ReadFile.class.getResourceAsStream("/config/testJava.java");//in为null
  70. // byte[] a=new byte[100];
  71. // in.read(a, 0, 900);
  72. // System.out.println("读取src下config包中的testJava.java的输入流in的内容toString:"+in.toString());
  73. // System.out.println("读取到的a:"+a);
  74. String fileName3 = ReadFile. class.getResource( "/config/test.properties").getFile();
  75. System.out. println( "读取src下config包中的test.properties:"+fileName3);
  76. //输出:读取src下config包中的test.properties:/D:/tomcat7/wtpwebapps/demoProj/WEB-INF/classes/config/test.properties
  77. // in.close();
  78. // 读取src下 基名为myproperties的properties文件,获取其中name配置值
  79. String value = ResourceBundle.getBundle( "myproperties").getString( "name");
  80. System.out. println( "获取到的myproperties.properties的值value:"+value);
  81. //输出:获取到的myproperties.properties的值value:myname
  82. // 读取src下myproperties.properties
  83. InputStream in1 = ReadFile. class.getResourceAsStream( "/myproperties.properties");
  84. Properties properties = new Properties();
  85. properties.load(in1);
  86. String value2 = properties.getProperty( "name"); // 得到name属性
  87. System.out. println( "获取到的myproperties.properties的值value2:"+value2);
  88. //获取到的myproperties.properties的值value2:myname
  89. //读取src下的
  90. String sensitiveWordsServerPath1 = SysConfig.getSysParam( "sensitiveWords_server_path1");
  91. System.out. println( "获取的sensitiveWordsServerPath1:"+sensitiveWordsServerPath1);
  92. //获取的sensitiveWordsServerPath1:/datacms/htdocs/html/cctv/sensitiveWords/sws.xlsx
  93. //读取src下的
  94. String pp = prop( "sensitiveWords_server_path1");
  95. System.out. println( "pp:"+pp); //pp:/datacms/htdocs/html/cctv/sensitiveWords/sws.xlsx
  96. }
  97. public String prop( String url){
  98. InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream( "config/sysconfig.properties");
  99. Properties p = new Properties();
  100. try {
  101. p.load(inputStream);
  102. } catch ( Exception e) {
  103. e.printStackTrace();
  104. }
  105. System.out. println( "p:"+p);
  106. return p.getProperty(url);
  107. }
  108. /**
  109. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  110. */
  111. protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  112. // TODO Auto-generated method stub
  113. doGet(request, response);
  114. String path = request.getSession().getServletContext().getRealPath( "/config/sysconfig.properties");
  115. System.out. println( "doPost:path:"+path);
  116. }
  117. }


网上大量的读取配置文件的都是从src目录下,只有如下是从WebContent目录下读取的:css


        
        
  1. String path = request.getSession().getServletContext().getRealPath( "/config/sysconfig.properties");
  2. System.out.println( "doGet读取到的/WEB-INF/config/sysconfig.properties:path:"+path);
  3. String url = request.getSession().getServletContext().getRealPath( "/WEB-INF/config/config.properties");
  4. System.out.println( "doGet读取到的/WEB-INF/config/config.properties:url:"+url);
  5. /**
  6. * 结果:
  7. * doGet:path:D:\tomcat7\wtpwebapps\demoProj\config\sysconfig.properties
  8. * doGet:url:D:\tomcat7\wtpwebapps\demoProj\WEB-INF\config\config.properties
  9. */

另:目前还没发现能够不启动tomcat,直接从当前项目WebContent目录下读取配置文件的简便方法。(不是从硬盘目录下,有些方法很复杂),有解决方法的同窗请贡献出来。html


参考:

http://blog.csdn.net/qhwc2009/article/details/45824815java

http://blog.csdn.net/wjl_mgqs/article/details/7554741
python

http://www.cnblogs.com/duoting/p/4141044.html
mysql

http://blog.csdn.net/mar_ljh/article/details/39693979
linux


附上SysConfig.javanginx


        
        
  1. package utils.readFile;
  2. import java.io.FileOutputStream;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.util.Properties;
  8. import org.apache.log4j.Logger;
  9. import com.alibaba.fastjson.JSONArray;
  10. import com.alibaba.fastjson.JSONObject;
  11. public class SysConfig {
  12. private static Logger logger = Logger.getLogger(SysConfig.class);
  13. /**
  14. * 将本类定义为singleton类
  15. */
  16. private SysConfig(){
  17. }
  18. private static SysConfig mConfig= new SysConfig();
  19. private Map<String,String> params = null;
  20. private static String CONFIG_FILE= "/config/sysconfig.properties";
  21. private static String CONFIG_FILE_PATH = SysConfig.class.getClassLoader().getResource( "").getPath().substring( 1) + CONFIG_FILE;
  22. public static String getSysParam(String param) {
  23. return getAllParams(). get(param);
  24. }
  25. public static Map<String,String> getAllParams() {
  26. synchronized(mConfig){
  27. if(mConfig. params== null){
  28. mConfig.readConfig();
  29. }
  30. }
  31. System. out.println( "mConfig.params:"+mConfig. params);
  32. return mConfig. params;
  33. }
  34. /**
  35. * 重载配置文件
  36. */
  37. public static void reloadConfig(JSONArray array) {
  38. try{
  39. Properties props = new Properties();
  40. for( int i= 0;i<array.size();i++){
  41. JSONObject o = array.getJSONObject(i);
  42. String key = o.keySet().iterator().next();
  43. String value = o.getString(key);
  44. mConfig. params.put(key, value);
  45. props.setProperty(key, value);
  46. }
  47. String configFilePath = CONFIG_FILE_PATH;
  48. if(!isLocal()){
  49. configFilePath = "/" + CONFIG_FILE_PATH;
  50. }
  51. OutputStream out = new FileOutputStream(configFilePath);
  52. props.store( out, "update");
  53. } catch(Exception e){
  54. logger.info( "may error config");
  55. }
  56. }
  57. private void readConfig() {
  58. try {
  59. Properties props = new Properties();
  60. props.load(SysConfig.class.getResourceAsStream(CONFIG_FILE));
  61. this.propertisToCache(props);
  62. } catch (Exception e) {
  63. logger.info( "may error config");
  64. }
  65. }
  66. /**
  67. * 将配置写入内存
  68. * @param properties
  69. */
  70. private void propertisToCache(Properties props){
  71. mConfig. params = new HashMap<String,String>();
  72. Enumeration e = props.propertyNames();
  73. while(e.hasMoreElements()) {
  74. String key = (String)e.nextElement();
  75. String value = props.getProperty(key);
  76. params.put(key, value);
  77. }
  78. if(isLocal()) {
  79. params.put( "root_path", params. get( "root_path_local"));
  80. params.put( "root_path_issue_temp", params. get( "root_path_issue_temp_local"));
  81. params.put( "root_path_issue", params. get( "root_path_issue_local"));
  82. } else {
  83. params.put( "root_path", params. get( "root_path_server"));
  84. params.put( "root_path_issue_temp", params. get( "root_path_issue_temp_server"));
  85. params.put( "root_path_issue", params. get( "root_path_issue_server"));
  86. }
  87. }
  88. /**
  89. * 判断系统类型
  90. * @return:true为windows系统
  91. */
  92. public static boolean isLocal() {
  93. if (System.getProperty( "os.name").contains( "Windows")) {
  94. return true;
  95. }
  96. logger.info( "os is : " + System.getProperty( "os.name"));
  97. return false;
  98. }
  99. }



逝魂影 关注
逝魂影

49篇文章

排名:千里以外

划船不用桨全靠浪 关注
划船不用桨全靠浪

5篇文章

排名:千里以外

maomaoyu3211 关注
maomaoyu3211

487篇文章

排名:千里以外

赣江 关注
赣江

73篇文章

排名:千里以外

广告
广告
广告

没有更多推荐了,返回首页

举报

java web项目获取src和WebContent目录下的配置文件 - 透明大脑

最多只容许输入30个字