Java-Java中对配置数据的存储方案

以前的方式(getResourceAsStream)

直接读取资源文件

public class CreateVvvvid {
    public static Map<String, AtomicInteger> vvvvidCreateMap = new HashMap<String, AtomicInteger>();
    static {
        // 获取数据库配置文件
        java.util.Properties properties = PropertiesUtil.getProperties(
                CreateVvvvid.class.getResourceAsStream("/config/database.properties"));
        int maxVvvvid = 0;
        Connection conn = null;
        try {
            /**
             * 读取数据库连接参数
             */
            String driverName = (String) properties.get("database.driverClassName");
            String url = (String) properties.get("database.url");
            String root = (String) properties.get("database.username");
            String pwd = (String) properties.get("database.password");
            /**
             * 初始化数据库连接,获取当前vvvvid最大值
             */
            Class.forName(driverName);
            conn = DriverManager.getConnection(url, root, pwd);
            Statement stat = conn.createStatement();
            String sql = "SELECT MAX(vvvvid) AS vvvvid FROM tt_user WHERE vvvvid Like '25%'";
            ResultSet rst = stat.executeQuery(sql);
            while (rst.next()) {
                maxVvvvid = rst.getInt("vvvvid");
            }
            int max=0;
            // 如果找不到vvvvid则从0开始增涨
            if (0 != maxVvvvid) {
                //如果非零则截取字符,初始化自增长类
                String maxVvvvid1 = String.valueOf(maxVvvvid);
                //等进一步完善????????
                maxVvvvid1 = maxVvvvid1.substring(maxVvvvid1.indexOf('555 + 1);
                        max = Integer.parseInt(maxVvvvid1);
            }
            vvvvidCreateMap.put("1", new AtomicInteger(max+1));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            try {
                conn.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

对property文件读写工具

public class PropertiesUtil {
    /**
     * 获取Properties对象(默认为utf-8字符编码)
     * @param filePath 件路径 
     * @return
     */
    public static Properties getProperties(String filePath) {
        return getProperties(filePath, "utf-8");
    }
    /**
     * 获取Properties对象(默认为utf-8字符编码)
     * @author wei.luo
     * @param in 输入流
     * @return
     */
    public static Properties getProperties(InputStream in) {
        f(in == null){
            eturn null;
            // 定义properties对象 
            Properties props = new Properties();
            // 加载properties文件 
            try {
                props.load(new InputStreamReader(in,"utf-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return props;
        }
/**
 * 获取Properties对象 
 * @param filePath 件路径 
 * @param encoding 符编码 
 * @return
 */
    public static Properties getProperties(String filePath, String encoding) {
// 定义properties对象 
        Properties props = new Properties();
        try {
// 判断文件是否存在,如果不存在则创建文件
            File file = new File(filePath);
            File dirFile = new File(file.getParent());
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            Reader rd = new InputStreamReader(new FileInputStream(file),
                    encoding);
// 加载properties文件 
            props.load(rd);
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return props;
    }
    /**
     * 获取key对应的value值 默认为utf-8
     * @param filePath
     * @param name
     * @return
     */
    public static String readValue(String filePath,String name){
        return readValue(filePath,"utf-8", name);
    }
    /**
     * 获取key对应的value值 
     * @param filePath
     * @param encoding
     * @param name
     * @return
     */
    public static String readValue(String filePath,String encoding,String name){
        Properties props=getProperties(filePath,encoding);
        return props.getProperty(name);
    }
    /**
     * 写资源文件(默认为utf-8编码)
     * @param filePath 文件路径 
     * @param name 名称 
     * @param value 值 
     */
    public static void write(String filePath, String name, String value) {
        write(filePath, "utf-8", name, value);
    }
    /**
     * 写property文件 
     * @param filePath 文件路径 
     * @param encoding 文件编码 
     * @param name 名称 
     * @param value 值 
     */
    public static void write(String filePath, String encoding, String name,
                             String value) {
        try {
            Properties props = getProperties(filePath, encoding);
            props.setProperty(name, value);
            Writer osw = new OutputStreamWriter(new FileOutputStream(filePath),
                    encoding);
// 以适合使用load方法加载到Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流
// props.store(fos, "Update '" + parameterName + "' value");
            props.store(osw, "");
            osw.close();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 读取properties的全部信息 
     * @param filePath
     */
    public static HashMap readAll(String filePath) {
        return readAll(filePath, "utf-8");
    }
    /**
     * 读取properties的全部信息 
     * @param filePath 文件路径 
     * @param encoding 字符编码 
     */
    public static HashMap readAll(String filePath, String encoding) {
        HashMap map = new HashMap();
        Properties props = getProperties(filePath, encoding);
// 获取所有的key,放入枚举类型中 
        Enumeration en = props.propertyNames();
// 遍历枚举,根据key取出value 
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String property = props.getProperty(key);
// 将值放入key中 
            map.put(key, property);
        }
        return map;
    }
    public static void main(String[] args) {
        String filePath = "D://aaaa.properties";
        String name = "testaaaa";
        String parameterValue = "测试!!!";
        Object []obs={"ee","ff"};
// write(filePath, name, parameterValue);
        System.out.println(MessageFormat.format (readValue(filePath,name), obs));
    }
}

应用单例的方式

属性文件(pathConfig.properties)

lis.interface = http://aaaaa.vvvv.com/lis
listenok = true
listlistenok = true
property.path = WEB-INF/classes/config/properties/pathConfig.properties
parent.path = E:/workspaces3/vvvv/WebRoot/files
bak.parent.path = E:/workspaces3/vvvv/WebRoot/files
upload.child.path = upload
channel.pic.child.path = upload/old
channel.newpic.child.path = upload/new
channel.bigpic.child.path = upload/big
music.pic.child.path = upload
zip.child.path = zip
zip.publish.child.path =freeListHtml
music.down.pic.path =music/images

properties文件的映射类(pathConfig.java)

/**
 * @className:PathConfig.java
 * @classDescription:从属性文件中获取各种路径
 * @author:wei.luo
 * @createTime:2012-3-23
 */
public class PathConfig {
    /**
     * 初始给properties文件的路径赋值
     */
    //public static String PROPFILE_PATH = "../webapps/ayyc/WEB-INF/classes/config/properties/pathConfig.properties";
    public static String PROPFILE_PATH = "WEB-INF/classes/config/properties/pathConfig.properties";
    /**
     * 存放pathConfig.properties中的属性
     */
    private Properties props=null;
    /**
     * 试听下载地址
     */
    public static String LIS_INTERFACE="http://aaaaa.vvvv.com/lis";
    /**
     * 默认试听服务器ok
     */
    public static String LISTENOK = "true" ;
    /**
     * 榜单列表页试听
     */
    public static String LISTLISTENOK = "true" ;
    /**
     * 前端访问首页
     */
    public static String MOBILEINDEX="http://aaaaaaa. vvvv.com/mobile/index.html#a=gqxq" ;
    /**
     * 分离的文件的父目录的绝对地址
     */
    public static String PARENT_PATH=null;
    /**
     * 备份的分离的文件的父目录的绝对地址
     */
    public static String BAK_PARENT_PATH=null;
    /**
     * upload文件夹
     */
    public static String UPLOAD_CHILD_PATH="upload";
    /**
     * 频道内置图片的的存放路径
     */
    public static String CHANNEL_PIC_CHILD_PATH="upload/old";
    /**
     * 频道小图片的存放路径
     */
    public static String CHANNEL_NEWPIC_CHILD_PATH="upload/new";
    /**
     * 频道大图片的存放路径
     */
    public static String CHANNEL_BIGPIC_CHILD_PATH="upload/big";
    /**
     * 歌曲图片的存放路径
     */
    public static String MUSIC_PIC_CHILD_PATH="upload";
    /**
     * zip文件的存放路径
     */
    public static String ZIP_CHILD_PATH="zip";
    /**
     * zip文件的发布地址
     */
    public static String ZIP_PUBLISH_CHILD_PATH="freeListHtml";
    /**
     * 下载的music图片存放地址
     */
    public static String MUSIC_DOWN_PIC_PATH="music/images";
    /**
     * PathConfig对象
     */
    private static PathConfig pathconfig=null;
    /**
     * 把构造方法私有化
     * @param path    properties文件的物理路径
     */
    private PathConfig(String path){
        props=PropertiesUtil.getProperties(path, "utf-8");
        if(props!=null){
            setFileValue("PROPFILE_PATH","property.path");
            setFileValue("LISTENOK","listenok");
            setFileValue("LISTLISTENOK","listlistenok");
            setFileValue("MOBILEINDEX","mobileindex");
            setFileValue("LIS_INTERFACE","lis.interface");
            setFileValue("PARENT_PATH","parent.path");
            setFileValue("BAK_PARENT_PATH","bak.parent.path");
            setFileValue("UPLOAD_CHILD_PATH","upload.child.path");
            setFileValue("CHANNEL_PIC_CHILD_PATH","channel.pic.child.path");
            setFileValue("CHANNEL_NEWPIC_CHILD_PATH","channel.newpic.child.path");
            setFileValue("CHANNEL_BIGPIC_CHILD_PATH","channel.bigpic.child.path");
            setFileValue("MUSIC_PIC_CHILD_PATH","music.pic.child.path");
            setFileValue("ZIP_CHILD_PATH","zip.child.path");
            setFileValue("ZIP_PUBLISH_CHILD_PATH","zip.publish.child.path");
            setFileValue("MUSIC_DOWN_PIC_PATH","music.down.pic.path");
        }
    }
    /**
     * 给类的各个属性设值
     * @author wei.luo
     * @createTime 2012-3-31
     * @param fieldName 类属性名
     * @param namePath 路径的key名
     */
    private void setFileValue(String fieldName,String namePath) {
        String property_path=props.getProperty(namePath);
        if(StringUtils.isNotBlank(property_path)){
            //fieldName=property_path;
            try {
                Field field=PathConfig.class.getField(fieldName);
                field.set(String.class, property_path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 从属性文件中读取key、value,初始化PathConfig
     * @author wei.luo
     * @createTime 2012-3-24
     * @param path properties文件的物理路径
     */
    public static synchronized void initPathConfig(String path){
        if(pathconfig==null){
            pathconfig = new PathConfig(path);
        }
    }
    /**
     * 销毁pathconfig对象
     * @author wei.luo
     * @createTime 2012-3-31
     */
    public static void destroy(){
        if(pathconfig!=null){
            pathconfig=null;
        }
    }
}

属性控制类(pathConfigController.java)

/**
 * @className:PathConfigController.java
 * @classDescription:路径配置管理
 * @author:wei.luo
 * @createTime:2012-3-24下午09:19:32
 */
@Controller
@RequestMapping("/vvvv/pathConfig")
public class PathConfigController extends BaseController{
    /**
     * 注入commonService
     */
    @Autowired
    private ICommonService commonService;
    /**
     * 显示配置属性列表
     * @author wei.luo
     * @createTime 2012-3-30
     * @param request request请求参数
     * @param response response请求参数
     * @param model 模型
     * @return 返回列表页面
     */
    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request, HttpServletResponse response,Model model) {
        //销毁单例
        PathConfig.destroy();
        //初始化配置信息
        String propFilePath=this.getRealPath(request, PathConfig.PROPFILE_PATH);
        //初始化单例
        PathConfig.initPathConfig(propFilePath);
        Map<String, String> pathConfigMap = this.commonService.getFields2(PathConfig.class);
        Map<String,String> parentPathMap=new HashMap<String,String>();
        Map<String,String> childPathMap=new HashMap<String,String>();
        Map<String,String> otherConfigMap=new HashMap<String,String>();
        for(String key:pathConfigMap.keySet()){
            if(key.contains("PARENT")){
                parentPathMap.put(key, pathConfigMap.get(key));
            }
            else if(key.contains("CHILD")){
                childPathMap.put(key, pathConfigMap.get(key));
            }
            else{
                otherConfigMap.put(key,pathConfigMap.get(key));
            }
        }
        model.addAttribute("parentPathMap", parentPathMap);
        model.addAttribute("childPathMap", childPathMap);
        model.addAttribute("otherConfigMap", otherConfigMap);
        //String currentPage = request.getRequestURI().toString();
        //request.getSession().setAttribute("currentPage", currentPage);
        return "manage/systemManage/listConfig.jsp";
    }
    /**
     * 编辑配置属性
     * @author wei.luo
     * @createTime 2012-3-30
     * @param request request请求参数
     * @param response response请求参数
     * @param model 模 型
     * @param config 配置
     * @return 返回列表页面
     */
    @RequestMapping(value="/edit")
    public String editPathConfig(HttpServletRequest request, HttpServletResponse response,
                                 Model model,String config/*,@PathVariable("config") String config*/) {
        Assert.notNull(config, "No config specified");
        if(StringUtils.isBlank(config) || request==null || response==null){
//            String currentPage = (String) this.getSessionAttribute(request, "currentPage");
//            this.sendRedirect(response, currentPage);
            return this.list(request,response,model);
        }
        config=StringUtils.substringBetween(config, "[", "]");
        String configKey = config.split("@")[0];
        String configValue = config.split("@")[1];
        model.addAttribute("configKey", configKey);
        model.addAttribute("configValue", configValue);
        return "manage/systemManage/editConfig.jsp";
    }
    /**
     * 跳到添加配置属性页
     * @author wei.luo
     * @createTime 2012-3-30
     * @param request request请求
     * @param response    response请求
     * @param model    模型
     * @return 跳转到添加页面
     */
    @RequestMapping(value="/toAdd")
    public String addPathConfig(HttpServletRequest request, HttpServletResponse response,Model model){
        return "manage/systemManage/addConfig.jsp";
    }
    /**
     * 添加配置
     * @author wei.luo
     * @createTime 2012-3-31
     * @param request    request请求参数
     * @param response    response 请求参数
     * @param model    模型
     * @param configKey    键
     * @param configValue    值 
     * @return    返回列表页面
     */
    @RequestMapping(value = "/add")
    public String addConfig(HttpServletRequest request, HttpServletResponse response,
                            Model model, String configKey,String configValue) {
//        if(StringUtils.isNotBlank(configKey) && StringUtils.isNotBlank(configValue) && request!=null && response!=null){
//            try {
//                String propsPath=PathConfig.PROPFILE_PATH;
//                PathConfig.destroy();
//                PathConfig.initPathConfig(PathConfig.PROPFILE_PATH);
//                //--动态创建静态属性-------
//                
//                
//                PropertiesUtil.write(propsPath, configKey,configValue);
//            }catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return this.list(request,response,model);
    }
    /**
     * 修改配置属性
     * 注意要添加对properties文件的修改
     * @author wei.luo
     * @createTime 2012-3-30
     * @param request    request请求参数
     * @param response    response请求参数
     * @param model     模型
     * @param configKey 键
     * @param configValue 值
     * @return 返回列表页面
     */
    @RequestMapping(value = "/alter")
    public String changePathConfig(HttpServletRequest request, HttpServletResponse response,
                                   Model model, String configKey,String configValue) {
        List<String> messageList = new ArrayList<String>();
        if(StringUtils.isNotBlank(configKey) && StringUtils.isNotBlank(configValue) && request!=null && response!=null){
            String oldConfigValue = this.commonService.getFieldValue(PathConfig.class, configKey);
            String inDir=oldConfigValue+"/";
            String outDir=configValue+"/";
            try {
                if("PARENT_PATH".equals(configKey)){
                    FileUtil.copy(inDir, outDir);
                }
                else if(configKey.contains("CHILD_PATH")){
                    FileUtil.copy(PathConfig.PARENT_PATH+"/"+inDir,PathConfig.PARENT_PATH+"/"+outDir );
                }
            } catch (Exception e) {
                String message="拷贝"+inDir+"目录下文件到"+outDir+"目录下失败";
                messageList.add(message);
                e.printStackTrace();
            }
            //修改类中的static属性值
            this.commonService.changeFields(PathConfig.class, configKey,configValue);
            //修改properties文件中的属性值
            String propertyPath=this.getRealPath(request, PathConfig.PROPFILE_PATH);
            configKey=configKey.toLowerCase().replace("_", ".");
            PropertiesUtil.write(propertyPath, configKey, configValue);
            //重新销毁再加载
            PathConfig.destroy();
            PathConfig.initPathConfig(propertyPath);
            //request.getRequestDispatcher("manage/pathConfig/list.do").forward(request, response);
        }
        request.setAttribute("messageList", messageList);
        return this.list(request,response,model);
    }
    /**
     * 将路径切到tomcat容器
     * @author wei.luo
     * @createTime 2012-4-7
     * @param request    request请求
     * @param response    response请求
     * @param model    模型
     * @return 返回列表页
     */
    @RequestMapping(value = "/switch2tomcat")
    public String switch2tomcat(HttpServletRequest request, HttpServletResponse response,Model model){
        List<String> messageList = new ArrayList<String>();
        String parentKey = "PARENT_PATH";
        String bakParentKey = "BAK_PARENT_PATH";
        String oldConfigValue = this.commonService.getFieldValue(PathConfig.class, parentKey);
        String webRootPath=this.getRealPath(request, "");
        if(oldConfigValue.equals(webRootPath)){
            return this.list(request,response,model);
        }
        //更新配置类中的属性
        this.commonService.changeFields(PathConfig.class, bakParentKey,webRootPath);
        this.commonService.changeFields(PathConfig.class, parentKey,webRootPath);
        //把分离的文件拷到tomcat容器的webRoot目录下
        try {
            FileUtil.copy(oldConfigValue,webRootPath );
        } catch (Exception e) {
            String message="拷贝"+oldConfigValue+"到"+webRootPath+"下失败!";
            messageList.add(message);
            e.printStackTrace();
        }
        //获得properties属性文件的路径,并设置属性值
        String propertyPath=this.getRealPath(request, PathConfig.PROPFILE_PATH);
        parentKey=parentKey.toLowerCase().replace("_", ".");
        bakParentKey=bakParentKey.toLowerCase().replace("_", ".");
        PropertiesUtil.write(propertyPath,parentKey, webRootPath);
        PropertiesUtil.write(propertyPath,bakParentKey, oldConfigValue);
        //重新销毁再加载
        PathConfig.destroy();
        PathConfig.initPathConfig(propertyPath);
        request.setAttribute("messageList", messageList);
        return this.list(request,response,model);
    }
    /**
     * 从tomcat容器切回分离目录
     * @author wei.luo
     * @createTime 2012-4-7
     * @param request request请求
     * @param response response请求
     * @param model 模型
     * @return 列表页
     */
    @RequestMapping(value = "/switch2nginx")
    public String switch2nginx(HttpServletRequest request, HttpServletResponse response,Model model){
        List<String> messageList = new ArrayList<String>();
        String key = "PARENT_PATH";
        String tomcatPath = this.getRealPath(request, "");
        String nginxPath = PathConfig.BAK_PARENT_PATH;
        if(tomcatPath.equals(nginxPath)){
            return this.list(request,response,model);
        }
        Map<String, String> pathConfigMap = this.commonService.getFields2(PathConfig.class);
        for(String key1:pathConfigMap.keySet()){
            String inPath=tomcatPath+"/"+pathConfigMap.get(key1)+"/";
            String outPath=nginxPath+"/"+pathConfigMap.get(key1)+"/";
            if(key1.contains("CHILD")){
                try {
                    FileUtil.copy(inPath, outPath);
                } catch (IOException e) {
                    String message="拷贝"+inPath+"到"+outPath+"下失败!";
                    messageList.add(message);
                    e.printStackTrace();
                }
                try {
                    FileUtil.delete(inPath);
                } catch (Exception e) {
                    String message="删除"+inPath+"失败!";
                    messageList.add(message);
                    e.printStackTrace();
                }
            }
        }
        //获得properties属性文件的路径
        String propertyPath=this.getRealPath(request, PathConfig.PROPFILE_PATH);
        key=key.toLowerCase().replace("_", ".");
        PropertiesUtil.write(propertyPath,key, nginxPath);
        //重新销毁再加载
        PathConfig.destroy();
        PathConfig.initPathConfig(propertyPath);
        request.setAttribute("messageList", messageList);
        return this.list(request,response,model);
    }
}

页面(javascript & css)

<STYLE type=text/css>
    {
        FONT-SIZE
        :
                12px
    }
    #operatorTree A {
        COLOR: #566984;
        TEXT-DECORATION: none
    }
    .STYLE2 {
        font-size: x-large
    }
</STYLE>
<style type="text/css" media="all">
    body,div {
        font-size: 12px;
    }
    .rw{background-image: url(${ctx}/images/cs.jpg);}}
</style>
^_^ ^_^ ^_^
<script type="text/javascript">
    function changeCss(i)
    {
        var cn=document.getElementById("rw"+i).className;
        if(cn!="")
        {
            document.getElementById("rw"+i).setAttribute("oldclass", cn);
        }
        document.getElementById("rw"+i).className="rw"
    }
    function recoverCss(i)
    {
        var old=document.getElementById("rw"+i).setAttribute("oldclass");
        document.getElementById("rw"+i).className="";
        if(old!="")
        {
            document.getElementById("rw"+i).className=old;
        }
    }
</script>

页面(jsp)

<TABLE height="100%" cellSpacing=0 cellPadding=0 width="100%">
    <TBODY>
    <TR>
        <TD width=10 height=29><IMG src="${ctx }/vvvv/index/Left.files/bg_left_tl.gif"></TD>
        <TD style="FONT-SIZE: 18px; BACKGROUND-IMAGE: url(${ctx }/vvvv/images/bg_left_tc.gif); COLOR: white; FONT-FAMILY: system">路径配置</TD>
        <TD width=10><IMG src="${ctx }/vvvv/index/Left.files/bg_left_tr.gif"></TD>
    </TR>
    <TR>
        <TD colspan="3" style="PADDING-RIGHT: 10px; PADDING-LEFT: 10px; PADDING-TOP: 10px; BACKGROUND-COLOR: white" vAlign="top">
            <div style="margin-left:5%;float:left;display:inline-block;"><b><font color="green">父目录(绝对路径)</font></b></div>
            <TABLE class=gridView id=ctl00_ContentPlaceHolder2_GridView1
                   style="WIDTH: 100%; BORDER-COLLAPSE: collapse" cellSpacing=0 rules=all
                   border=0 >
                <TR >
                    <th class="gridViewHeader" scope="col">序号 </th>
                    <th class="gridViewHeader" scope="col">key</th>
                    <th class="gridviewHeader" scope="col">value</th>
                    <th class="gridviewHeader" scope="col">操作</th>
                </TR>
                <c:set var="i" value="1" />
                <c:forEach items="${parentPathMap}" var="pathConfig" varStatus="s">
                    <c:if test="${pathConfig.key ne '' && pathConfig.key ne null}" >
                        <tr id="rw${i}" onmouseover="changeCss(${i})" onmouseout="recoverCss(${i})">
                            <td >${i}</td>
                            <td >${pathConfig.key }</td>
                            <td>${pathConfig.value }</td>
                            <td><a href="${ctx}/vvvv/pathConfig/edit.do?config=[${pathConfig.key}@${pathConfig.value }]" >编辑</a> <!-- |
                     <a href="#" onclick="if(confirm( '你确定删除吗? '))location.href='${ctx}/vvvv/pathConfig/delete?configName=${pathConfig.key }';return false;">删除</a> -->
                            </td>
                        </tr>
                        <c:set var="i" value="${i+1}" />
                    </c:if>
                </c:forEach>
                <!-- 结束 -->
            </TABLE>
        </TD>
    </TR>
    <TR>
        <TD colspan="3" style="PADDING-RIGHT: 10px; PADDING-LEFT: 10px; BACKGROUND-COLOR: white">
            <div style="margin-left:5%;float:left;display:inline-block;"><b><font color="green">子目录</font></b></div>
            <TABLE class=gridView id=ctl00_ContentPlaceHolder2_GridView1
                   style="WIDTH: 100%; BORDER-COLLAPSE: collapse" cellSpacing=0 rules=all
                   border=0 >
                <TR >
                    <th class="gridViewHeader" scope="col">序号 </th>
                    <th class="gridViewHeader" scope="col">key</th>
                    <th class="gridviewHeader" scope="col">value</th>
                    <th class="gridviewHeader" scope="col">操作</th>
                </TR>
                <c:set var="j" value="100" />
                <c:forEach items="${childPathMap}" var="pathConfig" varStatus="s">
                    <c:if test="${pathConfig.key ne '' && pathConfig.key ne null}" >
                        <tr id="rw${j}" onmouseover="changeCss(${j})" onmouseout="recoverCss(${j})">
                            <td >${j}</td>
                            <td >${pathConfig.key }</td>
                            <td>${pathConfig.value }</td>
                            <td><a href="#" onclick="if(confirm( '你确定要编辑子目录吗?(建议不要编辑子目录) '))location.href='${ctx}/vvvv/pathConfig/edit.do?config=[${pathConfig.key}@${pathConfig.value }]'" >编辑</a> <!-- |
                         <a href="#" onclick="if(confirm( '你确定删除吗? '))location.href='${ctx}/vvvv/pathConfig/delete?configName=${pathConfig.key }';return false;">删除</a> -->
                            </td>
                        </tr>
                        <c:set var="j" value="${j+1}" />
                    </c:if>
                </c:forEach>
                <!-- 结束 -->
            </TABLE>
        </TD>
    </TR>
    <TR>
        <TD colspan="3" style="PADDING-RIGHT: 10px; PADDING-LEFT: 10px; BACKGROUND-COLOR: white">
            <div style="margin-left:5%;float:left;display:inline-block;"><b><font color="green">其它配置</font></b></div>
            <TABLE class=gridView id=ctl00_ContentPlaceHolder2_GridView1
                   style="WIDTH: 100%; BORDER-COLLAPSE: collapse" cellSpacing=0 rules=all
                   border=0 >
                <TR >
                    <th class="gridViewHeader" scope="col">序号 </th>
                    <th class="gridViewHeader" scope="col">key</th>
                    <th class="gridviewHeader" scope="col">value</th>
                    <th class="gridviewHeader" scope="col">操作</th>
                </TR>
                <c:set var="k" value="200" />
                <c:forEach items="${otherConfigMap}" var="pathConfig" varStatus="s">
                    <c:if test="${pathConfig.key ne '' && pathConfig.key ne null}" >
                        <tr id="rw${k}" onmouseover="changeCss(${k})" onmouseout="recoverCss(${k})">
                            <td >${k}</td>
                            <td >${pathConfig.key }</td>
                            <td>${pathConfig.value }</td>
                            <td><a href="${ctx}/vvvv/pathConfig/edit.do?config=[${pathConfig.key}@${pathConfig.value }]" >编辑</a> <!-- |
                         <a href="#" onclick="if(confirm( '你确定删除吗? '))location.href='${ctx}/vvvv/pathConfig/delete?configName=${pathConfig.key }';return false;">删除</a> -->
                            </td>
                        </tr>
                        <c:set var="k" value="${k+1}" />
                    </c:if>
                </c:forEach>
                <!-- 结束 -->
            </TABLE>
            <p><div style="margin-left:5%;float:right;display:inline-block;"><b><font color="red">
            <input type="button" onclick="if(confirm( '你确定要将分离的文件切到tomcat容器中去吗? '))location.href='${ctx}/vvvv/pathConfig/switch2tomcat.do'"
                   value="将分离的文件切回tomcat容器中"/>
            <input type="button" onclick="if(confirm( '你确定要将tomcat容器中可分离的文件切到nginx指定目录去吗? '))location.href='${ctx}/vvvv/pathConfig/switch2nginx.do'"
                   value="将tomcat容器中可分离的文件切到nginx指定目录"/>
        </font></b></div></p>
        </TD>
    </TR>
    <TR>
        <TD width=10><IMG src="${ctx }/vvvv/index/Left.files/bg_left_bl.gif"></TD>
        <TD style="BACKGROUND-IMAGE: url(${ctx }/vvvv/images/bg_left_bc.gif)"></TD>
        <TD width=10><IMG src="${ctx }/vvvv/index/Left.files/bg_left_br.gif"></TD>
    </TR>
    </TBODY>
</TABLE>

截图一张
截图一张

方案二

说明:把配置信息,存储在配置的Bean中,再把Bean以集合的形式存储于Map当中,再将Map转成Json字符串,存储于集合当中。
配置工具类 : 配置工具类,用于获得配置信息存储配置信息。

ConfigUtil.java

package com.vvvv.musicsns.util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vvvv.musicsns.bean.ConfigBean;
import com.vvvv.musicsns.config.FinalConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
/**
 * config util 配置工具类
 * User: luowei
 * Date: 12-7-8
 * Time: 下午5:54
 */
public class ConfigUtil {
    /**
     * 记录器
     */
    protected static Logger logger = (Logger) LoggerFactory.getLogger(ConfigUtil.class);
    /**
     * ConfigUtil实例
     */
    private static ConfigUtil configUtil = null;
    /**
     * config json string,converted from Map<String,ConfigBean<T>>
     */
    private String configJson =null;
    /**
     * 配置工具类的map
     */
    private Map<String,ConfigBean> configBeanMap = new HashMap<String, ConfigBean>();
    /**
     * 构造方法
     * @param configJson json字符串
     */
    private ConfigUtil(String configJson){
        this.configJson = configJson;
    }
    /**
     * 拿配置文件路径
     * @return 返回路径
     */
    public static String getConfigFilePath(){
        String configFilePath = FinalConfig.class.getResource(FinalConfig.CONFIG_JSONFILE_NAME).getPath().substring(1);
// 判断系统 linux,windows
        if ("\\".equals(File.separator)){
            configFilePath = configFilePath.replace("%20" , " ");
        }else if ( "/".equals(File.separator)){
            configFilePath = "/"+ configFilePath.replace("%20" , " ");
        }
        return configFilePath;
    }
    /**
     * get configJson string , sington
     * @return 配置的json字符串
     */
    public static String getConfigJson() {
        return configUtil.configJson;
    }
    /**
     * set configJson string to config file
     * @param configJson 配置的json字符串
     * @return 成功或失败
     */
    public static Boolean setConfigJson(String configJson) {
        String filePath = getConfigFilePath();
        if(configUtil==null){
            configUtil = initConfigUtil();
        }
        configUtil.configJson = configJson;
        Boolean flag = FileUtil.writeString2File(filePath, configJson);
        return flag;
    }
    /**
     * get config bean Map<String,ConfigBean<T>> ,such as: <configBean.getKey(),configBean>
     * @return 配置信息map
     */
    public static Map<String,ConfigBean> getConfigMap(){
        if(null == configUtil){
            initConfigUtil();
        }
        String configStr = ConfigUtil.getConfigJson();
        if(StringUtils.isNotBlank(configStr)){
            Gson gson = new Gson();
            Type configBeanType = new TypeToken<Map<String,ConfigBean>>(){}.getType();
            configUtil.configBeanMap = gson.fromJson(configStr,configBeanType);
        }
        return configUtil.configBeanMap;
    }
    /**
     * set configBeanMap to config file
     * @param configBeanMap ConfigBean的map
     * @return 成功或失败
     */
    public static Boolean setConfigMap(Map<String,ConfigBean> configBeanMap){
        if(null == configUtil){
            initConfigUtil();
        }
        Gson gson = new Gson();
        String configStr = gson.toJson(configBeanMap);
        configUtil.configBeanMap = configBeanMap;
        Boolean flag = ConfigUtil.setConfigJson(configStr);
        return flag;
    }
    /**
     * init configUtil instance
     * @return 配置实例
     */
    private static synchronized ConfigUtil initConfigUtil(){
//if(configUtil==null){
        String configFilePath = getConfigFilePath();
        String jsonStr = FileUtil.readStringFromFile(configFilePath);
        configUtil = new ConfigUtil(jsonStr);
// }
        return configUtil;
    }
    /**
     * destroy configUtil instance
     */
    public static synchronized void destroy(){
        if(configUtil !=null){
            configUtil=null;
        }
    }
}

配置名称标识
配置的名称标识,标识了配置的名称,用于程序拿出指定的名称的配置。

FinalConfig.java

package com.vvvv.musicsns.config;
/**
 * the config properties defined in this class
 * User: luowei
 * Date: 12-7-8
 * Time: 下午1:08
 */
public class FinalConfig {
    public static String AAAAA = "aaaaa";
    public static String BBBBB = "bbbbb";
    public static String CCCCC = "ccccc";
}

配置Bean ConfigBean.java

package com.vvvv.musicsns.bean;
import java.io.Serializable;
/**
 * config bean ,to store config info
 * User: luowei
 * Date: 12-7-8
 * Time: 下午1:13
 */
public class ConfigBean implements Serializable {
    /**
     * 配置名称
     */
    protected String name;
    /**
     * key值
     */
    protected String key;
    /**
     * value值
     */
    protected String value;
    /**
     * 描述信息
     */
    protected String describe;
…………getset方法…………
}

使用 config.json

{
  "aaaaa": {
    "key": "aaaaa",
    "name": "域名",
    "value": "http://aa.com/aaaa",
    "describe": "音乐社区域名,外网:http://aa.vvvv.com"
  },
  "bbbbb": {
    "key": "bbbbb",
    "name": "域名",
    "value": "http://aa.com/aaaa",
    "describe": "音乐社区域名,外网:http://aa.vvvv.com"
  },
  "ccccc": {
    "key": "ccccc",
    "name": "域名",
    "value": "http://aa.com/aaaa",
    "describe": "音乐社区域名,外网:http://aa.vvvv.com"
  }
}

版权所有,转载请注明出处 luowei.github.io.