2008-05-01

struts按需重新載入配置文件

关键字: struts
struts 按需重新載入配置文件,查了好久整理下供大家参考

package com.aa.util;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionServlet;

public class StrustUtil {
	/**
	 * 得到所有strust配置文件的修改时间戳的和,以此来确定有没有修改过配置文件
	 * @param configFileNames
	 * @param webRootPath
	 * @return
	 */
	public static Long getStrutsConfigTimestamp(String[] configFileNames,
			String webRootPath) {
		Long strutsConfigTimestamp = 0L;
		for (String fileName : configFileNames) {
			fileName = fileName.trim();
			File strutsConfig = new File(webRootPath, fileName);
			if (strutsConfig.exists())
				strutsConfigTimestamp += strutsConfig.lastModified();
		}
		return strutsConfigTimestamp;
	}

	/**
	 * 自动重载strust配置文件,
	 * @param context
	 * @throws ServletException
	 */
	public static void reloadConfig(ServletContext context) throws ServletException {
		Long currentTimeStamp = (Long) context
				.getAttribute("STRUSTCONFIGFILE_LASTMODIFY");
		ActionServlet as = (ActionServlet) context
				.getAttribute(Globals.ACTION_SERVLET_KEY);
		String configString = as.getInitParameter("config");
		String[] configFileNames = configString.split(",");
		String realPath = context.getRealPath("/");
		Long strutsConfigTimestamp = getStrutsConfigTimestamp(configFileNames,
				realPath);
		if (currentTimeStamp != null
				&& !currentTimeStamp.equals(strutsConfigTimestamp)) {
			// 如果不相等重新载入配置文件
			as.destroy();
			context.removeAttribute(Globals.REQUEST_PROCESSOR_KEY);
			as.init();
		}
		context.setAttribute("STRUSTCONFIGFILE_LASTMODIFY",
				strutsConfigTimestamp);
	}
}

评论
发表评论

您还没有登录,请登录后发表评论

ccmv
搜索本博客
最近加入圈子
存档
最新评论