Jsp獲取Properties配置文件、java類獲取配置文件

1、JSP獲取配置文件

<%@ page contentType="text/html; charset=UTF-8" import="java.util.ResourceBundle" %>
<script type="text/javascript">
     <%ResourceBundle res = ResourceBundle.getBundle("setTime"); %>  <!--這裏填寫properties文件的名稱-->
     <%String socketUrl = res.getString("simpleTimer.timer"); %>
     var socketUrl = "<%=socketUrl %>";
     console.log(socketUrl); 
</script>

2、Jsp獲取當前項目路徑,

在jsp頂部添加以下代碼

①、<% 
    String path1 = request.getContextPath(); 
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/"; 
%> 

②、<%
	pageContext.setAttribute("APP_PATH", request.getContextPath());
	String path = request.getScheme() + "://" + request.getServerName()
	        + ":" + request.getServerPort() + request.getContextPath()
	        + "/";
	pageContext.setAttribute("path", path);
%>

使用時:

①、var url2='<%=basePath%>';

②、<img class="pimg" src="${APP_PATH}/static/images/a14053fbf3501dd586cd466edf280a68.jpg" width="200px"  height="200px"/> 

3、Java類獲取properties文件

public class GetProperty {  
    
    public GetProperty() {  
        super();  
    }  
  

    
    // 方法:通過類加載目錄getClassLoader()加載屬性文件    
    public static String getPropertyByName2(String path, String name) {    
        String result = "";    
    
        // 方法二:通過類加載目錄getClassLoader()加載屬性文件    
        InputStream in = GetProperty.class.getClassLoader()    
                .getResourceAsStream(path);    
        // InputStream in =    
        // this.getClass().getClassLoader().getResourceAsStream("mailServer.properties");    
    
        // 注:Object.class.getResourceAsStream在action中調用報錯,在普通java工程中可用    
        // InputStream in =    
        // Object.class.getResourceAsStream("/mailServer.properties");    
        Properties prop = new Properties();    
        try {    
            prop.load(in);    
            result = prop.getProperty(name).trim();    
          //  System.out.println("name:" + result);    
        } catch (IOException e) {    
            System.out.println("讀取配置文件出錯");    
            e.printStackTrace();    
        }    
        return result;    
    }    
      
  /*  public static void main(String[] args) {  
       // System.out.println("=="+GetProperty.getPropertyByName("dbconfig.properties","jdbc.jdbcUrl"));    
        System.out.println("==>>"+GetProperty.getPropertyByName2("dbconfig.properties","jdbc.jdbcUrl"));    
    }  */
}  

String timer=GetProperty.getPropertyByName2("setTime.properties","simpleTimer.timer");


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章