Struts2自定义初始化及Properties文件操作

利用Struts框架开发java web项目,需要进行自己的初始化工作。这个过程常常需要操作配置文件Properties,而且要求在系统初始化的阶段完成。

首先,需要建立properties文件:conf.properties,文件保存于src目录下。然后需要对该文件进行操作:

/*******************
 * read and write properties file
 * @author 60874
 *
 */
public class RWProp {

	private String propfile;

	protected String readProperty(String key) throws Exception {
		InputStream iStream = null;
		FileInputStream fis = null;
		try {
			Properties prop = new Properties();
			fis = new FileInputStream(propfile);
			iStream = new BufferedInputStream(fis);
			prop.load(iStream);
			return prop.getProperty(key);
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (iStream != null) {
				iStream.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	protected Map<String, String> readProperty() throws Exception{
		InputStream iStream = null;
		FileInputStream fis = null;
		try {
			Properties prop = new Properties();
			fis = new FileInputStream(propfile);
			iStream = new BufferedInputStream(fis);
			prop.load(iStream);
			Enumeration<String> en = (Enumeration<String>) prop.propertyNames();
			Map<String, String> propMap = new HashMap<String, String>();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String value = prop.getProperty(key);
				propMap.put(key, value);
			}
			return propMap;
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		}finally {
			if (fis != null) {
				fis.close();
			}
			if (iStream != null) {
				iStream.close();
			}
		}
	}

	protected Boolean writeProperties(String key, String value) throws Exception {
		if (key == null || key.trim().length() == 0) {
			throw new Exception("parameter: key can not be null!");
		}
		FileInputStream fis = null;
		OutputStream oStream = null;
		try {
			fis = new FileInputStream(propfile);
			Properties prop = new Properties();
			prop.load(fis);
			oStream = new FileOutputStream(propfile);
			prop.setProperty(key, value);
			prop.store(oStream, "Update " + key + " value");
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (oStream != null) {
				oStream.close();
			}
		}
	}

	protected int writeProperties(Map<String, String> propMap) throws Exception {
		if (propMap == null || propMap.size() == 0) {
			throw new Exception("parameter: propMap can not be null!");
		}
		FileInputStream fis = null;
		OutputStream oStream = null;
		try {
			fis = new FileInputStream(propfile);
			Properties prop = new Properties();
			prop.load(fis);
			oStream = new FileOutputStream(propfile);
			int count = 0;
			Iterator<Entry<String, String>> iterator = propMap.entrySet()
.iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				if (entry.getKey() != null && entry.getKey().length() > 0) {
					prop.setProperty(entry.getKey(), entry.getValue());
					prop.store(oStream, null);
					count ++;
				}
			}
			return count;
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (oStream != null) {
				oStream.close();
			}
		}
	}

	protected String getPropfile() {
		return propfile;
	}

	protected void setPropfile(String propfile) {
		this.propfile = propfile;
	}

}

该类可以读取、写入properties文件。这里的方法声明为protected,就是不希望外部的程序直接操作这些方法(尤其是修改配置文件的方法)。因为有些属性我们不希望外部应用程序直接修改。

于是,在此基础上,再封装一层,命名为Property。该类中对配置文件的各个项进行操作并对外提供接口。对于不希望外部修改的属性,其set方法置为private或protected。并在该类中创建init()方法和reload(), save()方法。

public static void init() {….}

public static void reload() {….}

public static void save() {….}

public static void save(String key, String value) {….}

======================================

以上是操作配置文件的封装。OK, 现在我们需要在系统启动的时候自动加载配置文件的信息。编写一个类,实现ServletContextListener接口。

public class InitSys implements ServletContextListener {

	private static Logger logger = Logger.getLogger(InitSys.class);

	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		logger.info("trying to initialize CMail >>>>>>");
		String propertyfile = sce.getServletContext().getRealPath(
				"/WEB-INF/classes/" + SParam.PROPERTY_FILE);
		Property.setPropfile(propertyfile);
		Property.init();
		logger.info("**********************");
		logger.info("CMAIL SYSTEM VERSION " + Property.getVersion());
		logger.info("Domain at: " + Property.getDomain());
		logger.info("**********************");
		logger.info("<<<<<< initialize CMail");
	}

}
然后在web.xml配置文件中配置该类,使得系统初始化时自动加载它。
<listener>
	<listener-class>com.csc.mail.jsh.config.inisys.InitSys</listener-class>
</listener>
DONE!
This entry was posted in Computer, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s