需要做一個參數(shù)初始化類,當(dāng)web應(yīng)用被加載時從數(shù)據(jù)庫里取出相關(guān)的參數(shù)設(shè)置
,并把這些參數(shù)放置到application里,jsp頁面可以從中取出。
1.在web.xml中配置:
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Dispatcher-
servlet.xml,/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>context</servlet-name>
<servlet-
class>org.springframework.web.context.ContextLoaderServlet</servlet-
class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>InitialServlet</servlet-name>
<servlet-
class>com.anylinks.billreturn.Web.InitialServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
2.servlet代碼
package com.anylinks.billreturn.Web;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import
org.springframework.web.context.support.WebApplicationContextUtils;
import com.anylinks.billreturn.BO.SysParameter;
import com.anylinks.billreturn.Service.ISysParameterService;
/*
* 初始化Servlet,從數(shù)據(jù)庫中讀取參數(shù)表,保存在application里
* @author 蔡科
* 創(chuàng)建日期:2006-1-9
*/
public class InitialServlet extends HttpServlet {
private Log log = LogFactory.getLog(this.getClass());
private ISysParameterService sysParameterService;
/**
* 從數(shù)據(jù)庫中讀取參數(shù)表,保存在application里
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
log.debug("start to intitail ");
// 獲取WebApplicationContext
ServletContext application = getServletContext();
WebApplicationContext wac = WebApplicationContextUtils
.getWebApplicationContext
(application);
// 調(diào)用sysParameterService取出所有的系統(tǒng)參數(shù)
sysParameterService = (ISysParameterService) wac
.getBean("sysParameterService");
Collection paras =
sysParameterService.findAllParameters();
log.debug("sys parameters size:" + paras.size());
// 把參數(shù)加到application里去
for (Iterator iter = paras.iterator(); iter.hasNext
();) {
SysParameter para = (SysParameter) iter.next
();
application.setAttribute(para.getParaName(),
para.getParaValue());
log.debug("initial parameter: key=" +
para.getParaName()
+ ", value=" +
para.getParaValue());
}
}
}
需要注意的地方:
1.僅僅配置一個DispatcherServlet是不夠的,我開始就是這樣,然后再servlet
里面怎么取都取不到WebApplicationContext 。配置上
org.springframework.web.context.ContextLoaderServlet之后才能取的到
WebApplicationContext 。
2.注意一下<load-on-startup>3</load-on-startup>,因?yàn)橛玫絪pring的
hibernateDaoSupport,所以必須在spring加載完之后再加載InitialServlet.