Java web利用配置文件脱离“硬编码”

来源:互联网 发布:淘宝店店铺介绍怎么写 编辑:程序博客网 时间:2024/06/03 20:04
今天在做项目的时候,老师突然问我是怎么解决项目中各处都要用到的一些常量,而且这些常量可能会随着部署地点和域名的变化发生相应变化。因为之前,这些常量都是在程序里面写死的,都没有想过这个问题;后来在老师的指导下,利用如下办法实现了相关常量的动态赋值。

1、定义一个常量类,类里面的field不要定义为final,应该定义为static,方便后面在程序启动的时候进行赋值。

public class CommonUtil {public static String SMS_URL;public static String SMS_UID;public static String SMS_KEY;}

2、定义一个配置文件common.properties,由于配置文件里有中文,为了解决乱码问题,将文件格式设置为“UTF-8”;在该文件中定义常量的值:

sms.url=http://www.baidu.com/sms.uid=我爱编程sms.key=123456

3、定义一个servlet,在程序启动的时候加载该servlet,在servlet中定义一个setInit()方法,根据路径加载上面定义的common.properties,利用Properties类的getProperties()方法获取配置文件里面定义的相关变量的值,将值赋给常量类里的相关field;在servlet的init()方法中调用该方法,即可完成在程序启动的时候完成常量的动态赋值。

package com.xxx.xxx.servlet;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xxx.xxx.util.CommonUtil;public class ConstantServlet extends HttpServlet {/** * 默认的构造器 */public ConstantServlet() {}/** *定义一个方法读取配置文件,并给静态常量赋值 */public void setInit(){//根据路径读取配置文件InputStream in = this.getServletContext().getResourceAsStream("src/main/resource/constant.properties");Properties pro = new Properties();Reader reader = null;try {//由于配置文件格式为"UTF-8",因此显示指明读取文件所使用的编码reader = new InputStreamReader(in, "UTF-8");pro.load(reader);//给常量类的属性赋值CommonUtil.SMS_URL=pro.getProperty("sms.url");CommonUtil.SMS_UID=pro.getProperty("sms.uid");CommonUtil.SMS_KEY=pro.getProperty("sms.key");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 在servlet初始化方法中调用上面的方法,实现在程序加载的时候调用该方法 */public void init() throws ServletException {this.setInit();}/** * servlet销毁方法 */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}/** * The doPost method of the servlet. <br> */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}}

4、最后,最重要一点,将该servlet添加到web.xml中,以便程序在启动的时候就加载该servlet。

0 0
原创粉丝点击