web.xml中配置启动时加载的servlet,load-on-starup


前阵子一直在搞前端结果搞得自己所学的java相关知识丢得一干二净。现在重新捡起来的时候,遇到N多问题,所以做笔记先。

这次项目中遇到我想搞清楚的小问题,就是项目加载后一些配置文件的读取,也就是启动的时候就将一些配置读到内存中以待使用。

使用servlet来初始化配置文件数据:

在servlet的配置当中,<load-on-startup>1</load-on-startup>的含义是:

标记容器是否在启动的时候就加载这个servlet。

当值为0或者大于0时,表示容器在应用启动时就加载这个servlet;

当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载。

正数的值越小,启动该servlet的优先级越高。

 

web.xml:

 

[plain]  view plain  copy
 
  1. <servlet>  
  2.         <servlet-name>StartServlet</servlet-name>  
  3.         <servlet-class>com.xtown.web.StartServlet</servlet-class>  
  4.         <load-on-startup>1</load-on-startup>  
  5.     </servlet>  



 

servlet代码:

 

[java]  view plain  copy
 
  1. public class StartServlet extends HttpServlet {  
  2.     private static final long serialVersionUID = 1L;  
  3.   
  4.     public void init() throws ServletException {  
  5.         JDBServlet is = new JDBServlet();  
  6.         is.ConfigFile = this.getClass().getClassLoader()  
  7.                 .getResourceAsStream("conf.xml");   //将文件转换为输入流  
  8.         is.start(); //设置从配置文件里读取过来的数据  
  9.   
  10.         String contextPath = getServletContext().getServletContextName();  
  11.         if (contextPath.endsWith("/"))  
  12.             contextPath = contextPath.substring(0, contextPath.length() - 1);  
  13.         getServletContext().setAttribute("path", "/" + contextPath);    //设置项目路径,用于设置绝对路径  
  14.     }  
  15. }  



 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM