js中獲取後臺properties文件中的值

js中獲取application.properties文件中的值

此示例是一個maven工程 , spring boot框架

想着用JQuery.i18n.properties插件 , 讀取src/main/resource下的properties文件 , 但是沒有成功 , 不知道是我寫的不對 , 還是就不能被讀取 , 也請看到此文的知道答案的告知下

此方案不行後 , 改變策略 , 在後臺讀取後 , 返回給前臺 .

即 發送一個ajax請求 , 後臺讀取properties文件後 , 返回一個Properties對象 , ajax以json格式接收

工程結構

index.js

$.ajax({
	url:"/getProperties",
	type:"GET",
	dataType:"json",
	success:function(data){
		alert(data["spring.datasource.driver-class-name"])
	}
})

PropertiesUtil.java

/**
 * 
 */
package com.cry.shop.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 讀取properties的工具類
 * @author CRY
 *
 */
public class PropertiesUtil {
    /**
     * 讀取properties
     *  
     * @param name 需要讀取的文件路徑
     * @return Properties
     */
    public static Properties getReadAbleProperties(String name) {

        InputStream ins = PropertiesUtil.class.getResourceAsStream(name);

        // 生成properties對象
        Properties p = new Properties();

        try {
            p.load(ins);
            ins.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return p;

    }

}

PropertiesController.java

package com.cry.shop.controller.front;

import java.util.Properties;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cry.shop.utils.PropertiesUtil;

@Controller
public class PropertiesController {
    @GetMapping("/getProperties")
    @ResponseBody
    public Properties getProperties() {
        Properties prop = PropertiesUtil.getReadAbleProperties("/application.properties");
        return prop;
    }
}

ApplicationController.java

package com.cry.shop.controller.front;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan(value = { "com.cry.shop.controller.*", "com.cry.shop.service.impl" })
@MapperScan(value = "com.cry.shop.mapper")
public class ApplicationController {
	public static void main(String[] args) {
		SpringApplication.run(ApplicationController.class, args);
	}
}

 

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