读书人

关于使用servlet来共享数据的有关问题

发布时间: 2012-09-09 09:27:54 作者: rapoo

关于使用servlet来共享数据的问题(系统起动就加载servlet)
在web系统开发中,常常要使用到一些共享数据:如:从xml文件中读取的内容需要共享.

实现:
1:在web.xml中配置启动时,加载serlvet
<!-- 初始化Servlet -->
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>com.servlet.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

2:InitServlet的实现
public class InitServlet extends HttpServlet
 {
   @Override
   private static String title;
public void init() throws ServletException
   {
    .....
     //在这里加载需要共享的内容,如加载xml中的内容
       //读取类路径下的helpDoc.properties文件
String helpConfigPath = getClassPath(this.getClass())
+ "helpDoc.properties";
Properties helpDocProps = readProperties(helpConfigPath);
      title = helpDocProps.getProperty("title")
   }
  
   @Override
public void destroy()
{
super.destroy();
}
 
 }


3:一些工具类的实现
  1):读取类路径下的文件:
     /**
*
* @param c
* @return
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unchecked")
public String getClassPath(Class c) throws   UnsupportedEncodingException
{
String contextPath = getServletContext().getRealPath("");
String rtnPath = contextPath + File.separator + "WEB-INF"
+ File.separator + "classes" + File.separator;
this.logFacility.log(Level.INFO, "class Path:[" + rtnPath + "]");
return rtnPath;
}


 
  2):读取properties文件
  /**
* 读取Properties文件
*/
public static Properties readProperties(String file)
{
InputStream in = null;
Properties prop = null;
try
{
in = new BufferedInputStream(new FileInputStream(file));
prop = new Properties();
prop.load(in);
}
catch (FileNotFoundException e1)
{
throw new RuntimeException(file + " is not exist!");
}
catch (IOException e)
{
throw new RuntimeException("Read file " + file + " error!");
}
finally
{
try
{
if (null != in)
{
in.close();
}
}
catch (IOException e)
{
in = null;
throw new RuntimeException("Close IO error!");
}
}
return prop;
}

读书人网 >软件架构设计

热点推荐