本文實例為大家分享了java項目啟動時執行指定方法,供大家參考,具體內容如下
想到的就是監聽步驟如下:
1.配置web.xml
1
2
3
|
< listener > < listener-class >com.listener.InitListener</ listener-class > </ listener > |
2.編寫InitListener類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package com.listener; import java.io.File; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.seegot.util.PropertyUtil; public class InitListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println( "================>[ServletContextListener]自動加載啟動開始." ); String resourceFilesPath = PropertyUtil.getProperty( "tempZipPath" ); clearFiles(resourceFilesPath); } // 刪除文件和目錄 private static boolean clearFiles(String workspaceRootPath) { File file = new File(workspaceRootPath); if (file.exists()) { deleteFile(file); } // resources 文件夾被刪除后需新建 if (!file.exists() && workspaceRootPath.endsWith( "resources" )) { return file.mkdir(); } else if (!file.exists()) { return true ; } return false ; } private static boolean deleteFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); for ( int i = 0 ; i < files.length; i++) { deleteFile(files[i]); } } return file.delete(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。