`

java review section

    博客分类:
  • java
 
阅读更多

 ===>个人总结:ListenerServlet的监听器,主要有对应的ServletContext的listener来监听ServletContext的情况,比如web 应用启动时会调用contextInitialized来初始化,应用关闭时调用contextDestroyed方法,还有对应的ServletContext的attribute发生变化时的Listener。====〉可以说是对ServletContext的监听。(application)

另一个就是通过HttpSessionListener来对session对象的创建销毁等进行监听,以及对属性的改变进行监听,有相对应的监听器来监听。

===〉所以监听器其实很简单, 那就是通过使用相对应的listener来监听servlet的servlet Context 和HttpSession对象的变化,仅此而已。但由于Servlet加载时会粗放ServletContextListener的contextInitialized,所以经常覆盖这个方法来初始化全局变量等,如spring那个ApplicationContext 对象。

 

 

ListenerServlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时,就激发sessionCreated(HttpSessionEvent se)方法,这样就可以给在线人数加1。常用的监听接口有以下几个:

ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改属性。

ServletContextListener监听ServletContext。当创建ServletContext时,激发contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。

HttpSessionListener监听HttpSession的操作。当创建一个Session时,激发session Created(HttpSessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。

HttpSessionAttributeListener监听HttpSession中的属性的操作。当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

 

 

 

###2listener能够监听到session,application的create,destroy,可以监听到session,application

属性绑定的变化 .====>session是HttpSession的一个引用,而 application为ServletContext的一个引用。

 ====>所以说listener能够监听session 和application对象 和以下ServeletContextListener的运用并无矛盾,

其实application对象就是ServletContext的一个对象,有相对应的ServletContextListener来监听整个servlet的上下文,比如初始化,destroy等。

 

ServletContextListener接口
[接口方法] contextInitialized()与 contextDestroyed()
[接收事件] ServletContextEvent
[触发场景] 在Container加载Web应用程序时(例如启动 Container之后),会呼叫contextInitialized(),而当容器移除Web应用程序时,会呼叫contextDestroyed ()方法。

ServletContextAttributeListener
[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
[接收事件] ServletContextAttributeEvent
[触发场景] 若有对象加入为application(S

ervletContext)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、attributeRemoved()。

 

===>对于ServletContextListener,在web.xml配置后,在web服务器如tomcat启动后便会加载并调用contextInitialized()这个方法,所以如果有需要在启动时便要初始化某些东西或启动哪个类都可以通过实现ServletContextListener来覆盖contextInitialized()来实现.

 

 

 

当Web工程启动时,定时器能自动开始计时,整个Web工程的生命期里,定时器每晚深夜触发一次任务。因此定时器的存放位置也值得考查,不能简单的存于单个Servlet或JavaBean,必须能让定时器宿主的存活期为整个Web工程生命期,工程启动时能自动加载运行。结合这两点,跟 Servlet上下文有关的侦听器就最合适不过了,通过工程的配置文件加以合理配置,会工程启动时自动运行,并整个工程生命期处于监听状态。

 

###1.

Servlet中的八大Listener

博客分类:

JSP/Servlet 中的事件处理写过AWT或Swing程序的人一定对桌面程序的事件处理机制印象深刻:通过实现Listener接口的类可以在特定事件(Event)发生时,呼叫特定的方法来对事件进行响应。

其实我们在编写JSP/Servle程序时,也有类似的事件处理机制,所不同的是在JSP/Servlet中是在web.xml中注册Listener,由Container在特定事件发生时呼叫特定的实现Listener的类。


1. Servlet中的Listener和Event:

在JSP 2.0/Servlet 2.4中,共有八个Listener接口,六个Event类别。
ServletContextListener接口
[接口方法] contextInitialized()与 contextDestroyed()
[接收事件] ServletContextEvent
[触发场景] 在Container加载Web应用程序时(例如启动 Container之后),会呼叫contextInitialized(),而当容器移除Web应用程序时,会呼叫contextDestroyed ()方法。

ServletContextAttributeListener
[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
[接收事件] ServletContextAttributeEvent
[触发场景] 若有对象加入为application(ServletContext)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、attributeRemoved()。

HttpSessionListener
[接口方法] sessionCreated()与sessionDestroyed ()
[接收事件] HttpSessionEvent
[触发场景] 在session (HttpSession)对象建立或被消灭时,会分别呼叫这两个方法。

HttpSessionAttributeListener
[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
[接收事件] HttpSessionBindingEvent
[触发场景] 若有对象加入为session(HttpSession)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、 attributeRemoved()。

HttpSessionActivationListener
[接口方法] sessionDidActivate()与 sessionWillPassivate()
[接收事件] HttpSessionEvent
[触发场景] Activate与Passivate是用于置换对象的动作,当session对象为了资源利用或负载平衡等原因而必须暂时储存至硬盘或其它储存器时(透过对象序列化),所作的动作称之为Passivate,而硬盘或储存器上的session对象重新加载JVM时所采的动作称之为Activate,所以容易理解的,sessionDidActivate()与 sessionWillPassivate()分别于Activeate后与将Passivate前呼叫。

ServletRequestListener
[接口方法] requestInitialized()与 requestDestroyed()
[接收事件] RequestEvent
[触发场景] 在request(HttpServletRequest)对象建立或被消灭时,会分别呼叫这两个方法。

ServletRequestAttributeListener
[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
[接收事件] HttpSessionBindingEvent
[触发场景] 若有对象加入为request(HttpServletRequest)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、 attributeRemoved()。

HttpSessionBindingListener
[接口方法] valueBound()与valueUnbound()
[接收事件] HttpSessionBindingEvent
[触发场景] 实现HttpSessionBindingListener接口的类别,其实例如果被加入至session(HttpSession)对象的属性中,则会呼叫 valueBound(),如果被从session(HttpSession)对象的属性中移除,则会呼叫valueUnbound(),实现HttpSessionBindingListener接口的类别不需在web.xml中设定。

2. 如何注册Servlet中的事件
实现上面这几个接口的类别,除了HttpSessionBindingListener外,必须在web.xml中向容器注册,容器才会在对应的事件发生时呼叫对应的类别,如:
< listener >
< listener-class > demo.servlet.listener.CustomServletContextListener

3. Servlet事件的应用实例

看到这里,你也许会有疑问: 了解这些 listener和event 有什么用呢?我平时开发没有用到这些,一样也能完成任务啊.

不错,在日常的开发中很少用到这些事件处理的方面,但是在某些情况下使用事件处理机制却可以达到事半功倍的效果,例如下面两个例子:

4.Java类实例
==========
//侦听启动和关闭
import javax.servlet.ServletContextListener;
import javax.servlet.*;

public class TigerListen implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce)
{
System.out.print("Init") ;
}
public void contextDestroyed(ServletContextEvent sce)
{
System.out.print("Destroved") ;
}
}

对应的web.xml是
============
< !----><listener></listener>
< listener-class></listener-class> TigerListen

============

 

####4.

由于工作需要,最近在找一些解决方案,发现Listener是一个很好的东西,

能够监听到session,application的create,destroy,可以监听到session,application

属性绑定的变化,考虑了一下,可以应用在"在线人数统计","数据缓存"等各个方面,

下面是整理的一些资料.


ListenerServlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时,就激发sessionCreated(HttpSessionEvent se)方法,这样就可以给在线人数加1。常用的监听接口有以下几个:

ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改属性。

ServletContextListener监听ServletContext。当创建ServletContext时,激发contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。

HttpSessionListener监听HttpSession的操作。当创建一个Session时,激发session Created(HttpSessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。

HttpSessionAttributeListener监听HttpSession中的属性的操作。当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

下面我们开发一个具体的例子,这个监听器能够统计在线的人数。在ServletContext初始化和销毁时,在服务器控制台打印对应的信息。当ServletContext里的属性增加、改变、删除时,在服务器控制台打印对应的信息。

要获得以上的功能,监听器必须实现以下3个接口:

HttpSessionListener

ServletContextListener

ServletContextAttributeListener

我们看具体的代码,见示例14-9。

【程序源代码】

1 // ==================== Program Discription =====================
2 // 程序名称:示例14-9 : EncodingFilter .java
3 // 程序目的:学习使用监听器
4 // ==============================================================
5 import javax.servlet.http.*;
6 import javax.servlet.*;
7
8 public class OnLineCountListener implements HttpSessionListener,
ServletContextListener,ServletContextAttributeListener
9 {
10 private int count;
11 private ServletContext context = null;
12
13 public OnLineCountListener()
14 {
15 count=0;
16 //setContext();
17 }
18 //创建一个session时激发
19 public void sessionCreated(HttpSessionEvent se)
20 {
21 count++;
22 setContext(se);
23
24 }
25 //当一个session失效时激发
26 public void sessionDestroyed(HttpSessionEvent se)
27 {
28 count--;
29 setContext(se);
30 }
31 //设置context的属性,它将激发attributeReplaced或attributeAdded方法
32 public void setContext(HttpSessionEvent se)
33 {
34 se.getSession().getServletContext().
setAttribute("onLine",new Integer(count));
35 }
36 //增加一个新的属性时激发
37 public void attributeAdded(ServletContextAttributeEvent event) {
38
39 log("attributeAdded('" + event.getName() + "', '" +
40 event.getValue() + "')");
41
42 }
43
44 //删除一个新的属性时激发
45 public void attributeRemoved(ServletContextAttributeEvent event) {
46
47 log("attributeRemoved('" + event.getName() + "', '" +
48 event.getValue() + "')");
49
50 }
51
52 //属性被替代时激发
53 public void attributeReplaced(ServletContextAttributeEvent event) {
54
55 log("attributeReplaced('" + event.getName() + "', '" +
56 event.getValue() + "')");
57 }
58 //context删除时激发
59 public void contextDestroyed(ServletContextEvent event) {
60
61 log("contextDestroyed()");
62 this.context = null;
63
64 }
65
66 //context初始化时激发
67 public void contextInitialized(ServletContextEvent event) {
68
69 this.context = event.getServletContext();
70 log("contextInitialized()");
71
72 }
73 private void log(String message) {
74
75 System.out.println("ContextListener: " + message);
76 }
77 }

 

 

在OnLineCountListener里,用count代表当前在线的人数,OnLineCountListener将在Web服务器启动时自动执行。当OnLineCountListener构造好后,把count设置为0。每增加一个Session,OnLineCountListener会自动调用sessionCreated(HttpSessionEvent se)方法;每销毁一个Session,OnLineCountListener会自动调用sessionDestroyed(HttpSessionEvent se)方法。当调用sessionCreated(HttpSessionEvent se)方法时,说明又有一个客户在请求,此时使在线的人数(count)加1,并且把count写到ServletContext中。ServletContext的信息是所有客户端共享的,这样,每个客户端都可以读取到当前在线的人数。

 


从作用域范围来说,Servlet的作用域有ServletContext,HttpSession,ServletRequest.

Context范围:

ServletContextListener:
对一个应用进行全局监听.随应用启动而启动,随应用消失而消失主要有两个方法:

contextDestroyed(ServletContextEvent event)

在应用关闭的时候调用

contextInitialized(ServletContextEvent event)

在应用启动的时候调用

这个监听器主要用于一些随着应用启动而要完成的工作,也就是很多人说的我想在容器
启动的时候干..........
一般来说对"全局变量"初始化,如

public void contextInitialized(ServletContextEvent event){
ServletContex sc = event.getServletContext();
sc.setAttribute(name,value);
}

以后你就可以在任何servlet中getServletContext().getAttribute(name);
我最喜欢用它来做守护性工作,就是在contextInitialized(ServletContextEvent event)
方法中实现一个Timer,然后就让应用在每次启动的时候让这个Timer工作:
程序代码:
public void contextInitialized(ServletContextEvent event){
timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
//do any things
}
},0,时间间隔);
}


有人说Timer只能规定从现在开始的多长时间后,每隔多久做一次事或在什么时间做
一次事,那我想在每月1号或每天12点做一项工作如何做呢?
你只要设一个间隔,然后每次判断一下当时是不是那个时间段就行了啊,比如每月一号做,那你
时间间隔设为天,即24小时一个循环,然后在run方法中判断当时日期new Date().getDate()==1
就行了啊.如果是每天的12点,那你时间间隔设为小时,然后在run中判断new Date().getHour()
==12,再做某事就行了.

ServletContextAttributeListener:

这个监听器主要监听ServletContex对象在setAttribute()和removeAttribute()的事件,注意
也就是一个"全局变量"在被Add(第一次set),replace(对已有的变量重新赋值)和remove的时候.
分别调用下面三个方法:
public void attributeAdded(ServletContextAttributeEvent scab)这个方法不仅可以知道
哪些全局变量被加进来,而且可获取容器在启动时自动设置了哪些context变量:
程序代码:
public void attributeAdded(ServletContextAttributeEvent scab){
System.out.println(scab.getName());
}
public void attributeRemoved(ServletContextAttributeEvent scab)

public void attributeReplaced(ServletContextAttributeEvent scab)


Session范围:
HttpSessionListener:
这个监听器主要监听一个Session对象被生成和销毁时发生的事件.对应有两个方法:
程序代码:
public void sessionCreated(HttpSessionEvent se)

public void sessionDestroyed(HttpSessionEvent se)


一般来说,一个session对象被create时,可以说明有一个新客端进入.可以用来粗略统计在线人
数,注意这不是精确的,因为这个客户端可能立即就关闭了,但sessionDestroyed方法却会按一定
的策略很久以后才会发生.

HttpSessionAttributeListener:
和ServletContextAttributeListener一样,它监听一个session对象的Attribut被Add(一个特定
名称的Attribute每一次被设置),replace(已有名称的Attribute的值被重设)和remove时的事件.
对就的有三个方法.
程序代码:
public void attributeAdded(HttpSessionBindingEvent se)

public void attributeRemoved(HttpSessionBindingEvent se)

public void attributeReplaced(HttpSessionBindingEvent se)


上面的几个监听器的方法,都是在监听应用逻辑中servlet逻辑中发生了什么事,一般的来说.
我们只要完成逻辑功能,比如session.setAttribute("aaa","111");我只要把一个名为aaa的变量
放在session中以便以后我能获取它,我并不关心当session.setAttribute("aaa","111");发生时
我还要干什么.(当然有些时候要利用的),但对于下面这个监听器,你应该好好发解一下:

HttpSessionBindingListener:
上面的监听器都是作为一个独立的Listener在容器中控制事件的.而HttpSessionBindingListener
对在一对象中监听该对象的状态,实现了该接口的对象如果被作为value被add到一个session中或从
session中remove,它就会知道自己已经作为一个session对象或已经从session删除,这对于一些非
纯JAVA对象,生命周期长于session的对象,以及其它需要释放资源或改变状态的对象非常重要.
比如:
session.setAttribute("abcd","1111");
以后session.removeAttribute("abcd");因为abcd是一个字符中,你从session中remove后,它就会
自动被垃圾回收器回收,而如果是一个connection:(只是举例,你千万不要加connection往session
中加入)
程序代码:
session.setAttribute("abcd",conn);

以后session.removeAttribute("abcd");这时这个conn被从session中remove了,你已经无法获取它
的句柄,所以你根本没法关闭它.而在没有remove之前你根本不知道什么时候要被remove,你又无法
close(),那么这个connection对象就死了.另外还有一些对象可以在被加入一个session时要锁定
还要被remove时要解锁,应因你在程序中无法判断什么时候被remove(),add还好操作,我可以先加锁
再add,但remove就后你就找不到它的句柄了,根本没法解锁,所以这些操作只能在对象自身中实现.
也就是在对象被add时或remove时通知对象自己回调相应的方法:
程序代码:
MyConn extends Connection implements HttpSessionBindingListener{
public void valueBound(HttpSessionBindingEvent se){
this.initXXX();
}
public void valueUnbound(HttpSessionBindingEvent se){

this.close();
}
}


session.setAttribute("aaa",new MyConn());
这时如果调用session.removeAttribute("aaa"),则触发valueUnbound方法,就会自动关闭自己.
而其它的需要改变状态的对象了是一样.

 

 

 

 

 

#1.listener 所监听的对象是Context,application,session等变化,当然spring经常用一个类来实现Servlet ContextListener来kick 动

ApplicationContext,以便我们能够get到service:

 

<listener>

 

 

 

<listener-class>com.acn.pmt.common.WebContextListener</listener-class>

 

</listener>

 

 

public

 

class WebContextListener implements ServletContextListener{

 

 

 

 

 

publicvoid contextDestroyed(ServletContextEvent event) {

 

 

 

 

 

}

@override

 

publicvoid contextInitialized(ServletContextEvent event) {

 

 

 

SpringConfig.init(event.getServletContext());

 

 

 

DataManage.getInstance();

 

 

 

}

 

 

 

}

 

 

 

public

 

class SpringConfig {

 

 

 

privatestatic ApplicationContext springContext;

 

publicstaticvoid init(ServletContext servletContext) {

 

springContext=WebApplicationContextUtils.getWebApplicationContext(servletContext);

 

}

 

 

 

publicstatic ApplicationContext getSpringContext(){

 

returnspringContext;

 

}

 

}


###2.serilize 只是表明远端那一块内存可以全部考过来(这个还不懂。。需进一步证明)

 

 

分享到:
评论

相关推荐

    java review guide java复习资料

    java 复习资料,很详细的说,考试面试前看看肯定有好处

    java review.rar

    java review.rar

    Java项目开发CodeReview 常见问题实例分析及指南

    CodeReview的基本手段还是需要技术经理通过人工检查项目成员的代码,来将各种问题扼杀在开发阶段,但是不同经验及技术水平的经理在review同一段代码所发现的问题可能相差比较大,不同的Team可能因此产生的效果也不同...

    Java项目开发代码Review常见问题实例.doc

    Java项目开发代码Review常见问题实例

    Java Code review checklist.doc

    Java Code review checklist

    java review

    java的复习还可以的啊,你们可以多多的看下的、

    java代码评审检查表.xls

    java代码评审检查表:包含java常用代码审查内容

    CodeReview工具Jupiter

    Code Review的作用和意义已在很多技术团队内达成共识,可是很多时候并未被有效执行,甚至被认为是一项费时费力的工作。借助一些工具可以更容易,更有效率地来进行Code Review,本文介绍的Jupiter即是其中之一。  ...

    [Java] Java 编程面试揭秘 英文版

    Review over 150 real world Java interview questions you are likely to encounter Prepare for personality based interviews as well as highly technical interviews Explore related topics such as ...

    Java.Interview.Bootcamp

    Section two is an in depth core Java review. Java interviews are really hard. For some reason interviewers love to ask complicated GC tuning questions, or challenge your knowledge on the Big O of ...

    2018秋招java笔试题-java_review:Java评论

    Review 1. 数据结构和算法 红黑树 代码: ) 图解: 2. 面试题 2021.4.10 英礡Improbable笔试题 (2021 Improbable Intern Online Test) 括号匹配 约瑟夫环 2021.03.31 华为校园招聘软件笔试题 2021.3.31 兴业数金Java...

    JAVA-EE-Review.zip_JAVA EE_JAVA EE

    JAVA EE复习,Java EE简介、JSP应用基础、Struts 2应用、Hibernate应用等

    code review(程序员必看)

    code review(程序员必看)code review(程序员必看)code review(程序员必看)

    Review of Java and object-oriented programming.ppt

    Review of Java and object-oriented programming.ppt

    CoreJava_Re

    CoreJava_Review

    ReviewBoard + Tao-ReviewBoard + SVN 搭建代码审阅平台

    ReviewBoard + Tao-ReviewBoard + SVN + Eclipse (Mars.2) 如果eclipse中配置好Tao-ReviewBoard点确定时报错说用户名密码错误可能的原因 1 真的是你的服务器配置错了 清下缓存 再试试 如果Tao-ReviewBoard安装好了...

    Review Assistant

    Review Assistant 是 Visual Studio 中的一个加载项工具,它的作用是帮你进行代码审查,这样可以大大简化程序员的工作,提高效率,并且检查出一些肉眼不容易看到的错误。一个项目三个人可以无限期试用。 Review ...

    Review Assistant (支持VS2019)

    Review Assistant 是 Visual Studio 中的一个加载项工具,它的作用是帮你进行代码审查,这样可以大大简化程序员的工作,提高效率,并且检查出一些肉眼不容易看到的错误。一个项目三个人可以无限期试用。 Review ...

    Modern Code Review- A Case Study at Google.pdf

    Employing lightweight, tool-based code review of code changes (aka modern code review) has become the norm for a wide variety of open-source and industrial systems. In this paper, we make an ...

    java代码审查规范文档

    Code Review是一种用来确认方案设计和代码实现的质量保证机制,通过这个机制我们可以对代码、测试过程和注释进行检查。 Code Review主要用来在软件工程过程中改进代码质量,通过Code Review可以达到如下目的: .在...

Global site tag (gtag.js) - Google Analytics