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);
}
}