1 构造函数==》postConstruct==>init==destory==>predestory==卸载servlet;;2
3 从Java EE5规范开始,Servlet增加了两个影响Servlet生命周期的注解(Annotation):@[email protected]个非静态的void()方法.而且这个方法不能有抛出异常声明。4
5 使用方式,例如:6
7
8 1 @PostConstruct //方式1
9 2 public voidsomeMethod(){10 3...11 4}12 5
13 6 public @PostConstruct void someMethod(){ //方式2
14 7...15 8}16
17 1.@PostConstruct说明18
19 [email protected]�候运行,并且只会被服务器调用一次,类似于Serclet的inti()[email protected],init()方法之前运行。20
21 2.@PreDestroy说明22
23 [email protected]�运行,并且只会被服务器调用一次,类似于Servlet的destroy()[email protected]()方法之后运行,在Servlet被彻底卸载之前。(详见下面的程序实践)24
25 3.程序实践26
27 web.xml28
29
30 1
31 2
32 3 AnnotationServlet
33 4 com.servlet.AnnotationServlet
34 5
35 6
36 7 AnnotationServlet
37 8 /servlet/AnnotationServlet
38 9
39
40 AnnotationServlet41
42 1 packagecom.servlet;43 2
44 3 importjava.io.IOException;45 4 importjava.io.PrintWriter;46 5 importjava.sql.Time;47 6 importjava.text.SimpleDateFormat;48 7 importjava.util.Date;49 8
50 9 importjavax.annotation.PostConstruct;51 10 importjavax.annotation.PreDestroy;52 11 importjavax.servlet.ServletException;53 12 importjavax.servlet.http.HttpServlet;54 13 importjavax.servlet.http.HttpServletRequest;55 14 importjavax.servlet.http.HttpServletResponse;56 15
57 16 public class AnnotationServlet extendsHttpServlet {58 17 SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");//设置日期格式,精确到毫秒
59 18
60 19 publicAnnotationServlet(){61 20 System.out.println("时间:"+df.format(new Date())+"执行构造函数...");62 21}63 22
64 23 public voiddestroy() {65 24 this.log("时间:"+df.format(new Date())+"执行destroy()方法...");66 25 //super.destroy();//Just puts "destroy" string in log
67 26 //Put your code here
68 27}69 28
70 29@PostConstruct71 30 public voidsomeMethod(){72 31 //this.log("[email protected]()方法...");//注意:这样会出错
73 32 System.out.println("时间:"+df.format(new Date())+"[email protected]()方法...");74 33}75 34
76 35@PreDestroy77 36 public voidotherMethod(){78 37 System.out.println("时间:"+df.format(new Date())+"[email protected]()方法...");79 38}80 39
81 40 public voiddoGet(HttpServletRequest request, HttpServletResponse response)82 41 throwsServletException, IOException {83 42 this.log("时间:"+df.format(new Date())+"执行doGet()方法...");84 43}85 44
86 45 public void init() throwsServletException {87 46 //Put your code here
88 47 this.log("时间:"+df.format(new Date())+"执行init()方法...");89 48}90 49
91 50 protected voidservice(HttpServletRequest request, HttpServletResponse response)92 51 throwsServletException, IOException{93 52 this.log("时间:"+df.format(new Date())+"执行service()方法...");94 53 super.service(request, response);95 54}96 55
97 56}98
99 运行结果:100
101
102
103 4.注意事项104
105 注解多少会影响服务器的启动速度。服务器在启动的时候,会遍历Web应用的WEB-INF/classes下的所有class文件与WEB-INF/lib下的所有jar文件,以检查哪些类使用了注解。如果程序中没有使用任何注解,可以在web.xml中设置的metadatacomplete属性为true来关掉服务器启动时的例行检查。106
107
108
109 支持注解的服务器需要支持到Servlet2.5及以上规范,所以Tomcat要6.0.X及以上版本才行。