There are two ways to use listeners in a Java Web program

Source: Internet
Author: User
Tags session id serialization java web

Before learning a lot of content involved in the servlet, this summary we say the listener, talking about the listener, the desktop program and mobile app are not unfamiliar, the common routine is to drag a control, and then bind it a listener, that the object can listen to the event to respond, Essentially, these are the specific implementations of the observer pattern, and the listener in the Web program is no exception.
There are two ways to use listeners in a Java Web program:
A custom listener is identified by the annotation @weblistener;
[Java] View plain copy
@WebListener
public class Customlistener implements Listener {

}
Use the listener by configuring it in Web. xml;
[HTML] View plain copy
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
In the Java Web program, support is provided primarily for ServletContext, HttpSession, and ServletRequest three objects.
First, ServletContext listener
There are two types of listeners that listen to ServletContext objects:
Servletcontextlistener: The listener is used to monitor servletcontext initialization and destruction events;
Servletcontextattributelistener: The listener is used to listen for the deletion, addition and substitution of attributes in the ServletContext;
Examples are as follows:
[Java] View plain copy
@WebListener
public class Myservletlistener implements Servletcontextlistener, Servletcontextattributelistener {
public void contextinitialized (Servletcontextevent sce) {
System.out.println ("servletcontextevent Source:" + sce.getsource (www.leyujiada.cn));
SYSTEM.OUT.PRINTLN ("context created");
}

public void contextdestroyed (Servletcontextevent sce) {
System.out.println ("servletcontextevent Source:" + sce.getsource ());
SYSTEM.OUT.PRINTLN ("context destroyed");
}

public void attributeadded (Servletcontextattributeevent event) {
System.out.println ("servletcontextattributeevent Source:" + event.getsource ());
SYSTEM.OUT.PRINTLN ("www.zjingjiyl.cn attribute added:" + event.getname () + "--" + event.getvalue ());
}

public void Attributeremoved (Servletcontextattributeevent event) {
System.out.println ("servletcontextattributeevent Source:" + www.txfenfenc11.cn Event.getsource ());
System.out.println ("attribute removed:" + event.getname () + "--" + event.getvalue ());
}

public void attributereplaced (Servletcontextattributeevent event) {
System.out.println ("servletcontextattributeevent Source:" + www.lieqibiji.com/event.getSource ());
System.out.println ("attribute replaced:www.chuangyed.com" + event.getname () + "--" + event.getvalue ());
}
}
This class implements the above two interfaces, initiates the servlet container, analyzes the results, and outputs the following:

You can see that ServletContext was first created during startup, which fired the contextinitialized listener method and then called each servlet's init () method to initialize each servlet. For all servlets (here are two custom servlet,myservlet,testservlet) when initialization is complete, a property is added to ServletContext, whether the event object or the added property is provided by the servlet container.
When the servlet container is closed, the results are analyzed and the output is as follows:

The Destroy method of all Servlets is called first, and then the ServletContext instance is destroyed.
When an attribute is added, replaced, or deleted, the appropriate listener is called, with the following code:
[Java] View plain copy
ServletContext context = Req.getservletcontext ();
Context.setattribute ("Country", "Zn");
Context.setattribute ("Country", "en");
Context.removeattribute ("Country");
Code output:

It is important to note that setattribute () is used when replacing attributes, except that the value of key is the same. When the property is replaced, the listener gets the old value (I think both the old value and the new value should provide the appropriate API).
Second, HttpSession Listener
There are four types of listeners that listen to HttpSession objects:
Httpsessionlistener: Used to monitor the creation and destruction of httpsession;
Httpsessionactivationlistener: This listener is used in a distributed environment, and this class is used when HttpSession instances are migrated or serialized between different virtual machines. The Sessiondidactivate () method is called when the HttpSession object is migrated to a new virtual machine or deserialized. The Sessionwillpassivate () method is called when the HttpSession instance is moved out or serialized from the old virtual machine;
Httpsessionattributelistener: Used to monitor the deletion, increment and substitution of attributes in the httpsession;
Httpsessionbindinglistener:
In fact, in the new Servlet3.1 specification There is also a session listener, Javax.servlet.http.HttpSessionIdListener for monitoring sessionid changes, because I use TOMCAT7 also does not support Servlet3.1 so Will not find this class, so there is no writing, if you are interested can try it yourself.
1, Httpsessionlistener and Httpsessionattributelistener:
[Java] View plain copy
@WebListener
public class Myhttpsessionlistener implements Httpsessionlistener, Httpsessionattributelistener {
Private Long StartTime;

public void attributeadded (Httpsessionbindingevent event) {
StartTime = (Long) event.getsession (www.tips139.com/). getattribute ("StartTime");

System.out.println ("httpsessionbindingevent Source:" + event.getsource ());
SYSTEM.OUT.PRINTLN ("Add attribute:" + event.getname () + "--" + event.getvalue ());
}

public void Attributeremoved (Httpsessionbindingevent event) {
System.out.println ("httpsessionbindingevent Source:" + event.getsource ());
SYSTEM.OUT.PRINTLN ("Remove attribute:" + event.getname () + "--" + event.getvalue ());
}

public void attributereplaced (Httpsessionbindingevent event) {
System.out.println ("httpsessionbindingevent Source:" + event.getsource ());
SYSTEM.OUT.PRINTLN ("Replace attribute:" + event.getname () + "--" + event.getvalue ());
}

public void sessioncreated (Httpsessionevent se) {
System.out.println ("httpsessionevent Source:" + se.getsource ());
SYSTEM.OUT.PRINTLN ("Session ID:" + se.getsession (). GetId ());
SYSTEM.OUT.PRINTLN ("session create");
}

public void sessiondestroyed (Httpsessionevent se) {
System.out.println ("httpsessionevent Source:" + se.getsource ());
SYSTEM.OUT.PRINTLN ("Session ID:" + se.getsession (). GetId ());
SYSTEM.OUT.PRINTLN ("Active Time:" + (System.nanotime ()-startTime));
SYSTEM.OUT.PRINTLN ("session Destroy");
}

}
The corresponding servlet is as follows:
[Java] View plain copy
@WebServlet (name= "Myhttpsessionservlet", urlpatterns= "/myhttpsessionservlet", Loadonstartup=1)
public class Myhttpsessionservlet extends HttpServlet {
Private static final long serialversionuid = 5687825632187950599L;
@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
HttpSession session = Req.getsession ();
Session.setattribute ("StartTime", System.nanotime ());

Session.setattribute ("Visittimes", 0);
Session.setattribute ("Visittimes", 1);
Session.removeattribute ("Visittimes");

Session.setmaxinactiveinterval (10);
Resp.getwriter (). Write ("Session Listene demo");
}

@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {

}
}
The first time you request resources for the site, the output is as follows:

You can see that the first time you create a httpsession, you call the Sessioncreated () method. The corresponding property listener is then triggered when the method is added, replacing the property or the pre-replacement value returned by the listener.
Since the time of survival is set, then the method of destroying session is triggered, and the output is as follows:

It is visible that the session is destroyed not just by calling the Sessiondestroyed () method, but after executing this method, the Attributeremoved () method is called and all properties saved in it are cleared.
2, Httpsessionactivationlistener
The listener, as mentioned above, works in a distributed environment or when a HttpSession instance is being serialized.
Because the session is stored in memory, sometimes the server in order to save memory, will be less access to the session to the storage device, including the file system and database, so that can save memory space, on the other hand also tells us not to put too much data in the session, To avoid the burden of the server;
When in a distributed environment, if a machine is not reachable, the session serialization can be transferred to other servers in the JVM to work, which requires storage in the session to the data can be serialized, this is used to this listener;
Serialization of the session is usually done by a servlet container, which we can configure;
Error, incorrect use:
[Java] View plain copy
HttpSession session = Req.getsession ();
Session.setattribute ("StartTime", System.nanotime ());
Session.setattribute ("Visittimes", 0);
Session.setattribute ("Visittimes", 1);
Session.removeattribute ("Visittimes");
ObjectOutputStream output =new ObjectOutputStream (new FileOutputStream ("C:\\demo"));
Output.writeobject (session);
The above is the wrong way to use, can not serialize HttpSession, the serialization here is only the session instance of the information into a network can be transmitted in the form of data, the meaning of the scope is greater than the concept of serialization in Java, the general understanding is to convert the object into a string.
As for why the session is serialized, it is obvious that if the server goes down, all the information on the client Access server is lost because it exists in memory, and the session is serialized to the storage device and the user information can be restored at the same time after the server resumes running.
3, Httpsessionbindinglistener
First of all, this listener is very similar to the previous Httpsessionattributelistener, but they have the following differences:
Httpsessionattributelistener to register, or through annotations or via Web. XML, it is used to listen to all session instances in the entire application, and all session instances corresponding to the properties, belong to a generic listener;
Httpsessionbindinglistener is a listener for a specific session and a specific property, is tailored, and it does not need to register;
Examples of usage are as follows:
[Java] View plain copy
public class person implements Serializable, httpsessionbindinglistener{
Private static final long serialversionuid = -4972586177179694554l;
private String name;
Private Integer age;

Public person () {}

Public person (String name, Integer age) {
Super ();
THIS.name = name;
This.age = age;
}

Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public Integer Getage () {
return age;
}
public void Setage (Integer age) {
This.age = age;
}

@Override
Public String toString () {
return "person [name=" + name + ", age=" + Age + "]";
}
public void Valuebound (Httpsessionbindingevent event) {
System.out.println ("Person bound");
}
public void Valueunbound (Httpsessionbindingevent event) {
System.out.println ("Person Unbound");
}
To add a property to the session in the Doget () method:
[Java] View plain copy
Session.setattribute ("person", new person ("Lmy", 23));
Session.setmaxinactiveinterval (10);
After making the request, the output is as follows:
[Java] View plain copy
Httpsessionbindingevent Source: [Email protected]
Person bound
Session expires after 10 seconds, output:
[Java] View plain copy
Httpsessionbindingevent Source: [Email protected]
Person Unbound
Third, ServletRequest listener
There are three types of listeners that listen to ServletRequest objects:
Servletrequestlistener: Used to monitor the creation and destruction of servletrequest, note that the servlet container is reused servletrequest through the pool, Creating an ServletRequest instance is actually taking an instance out of the pool, destroying the object and putting the instance back into the pool;
Servletrequestattributelistener: Used to monitor the deletion, increment and substitution of attributes in the ServletRequest;
Asynclistener: This later refers to the asynchronous programming when the detailed said;
The listener code is as follows:
[Java] View plain copy
@WebListener
public class Myservletrequestlistener implements Servletrequestlistener, Servletrequestattributelistener {

public void attributeadded (Servletrequestattributeevent srae) {
System.out.println ("servletrequestattributeevent Source:" + srae.getsource ());
SYSTEM.OUT.PRINTLN ("Request attribute added:" + srae.getname () + "--" + srae.getvalue ());
}

public void attributeremoved (Servletrequestattributeevent srae) {
System.out.println ("servletrequestattributeevent Source:" + srae.getsource ());
SYSTEM.OUT.PRINTLN ("Request attribute removed:" + srae.getname () + "--" + srae.getvalue ());
}

public void attributereplaced (Servletrequestattributeevent srae) {
System.out.println ("servletrequestattributeevent Source:" + srae.getsource ());
SYSTEM.OUT.PRINTLN ("request attribute replaced:" + srae.getname () + "--" + srae.getvalue ());
}

public void requestdestroyed (Servletrequestevent sre) {
System.out.println ("servletrequestevent Source:" + sre.getsource ());
SYSTEM.OUT.PRINTLN ("Request Destroy");
}

public void requestinitialized (Servletrequestevent sre) {
System.out.println ("servletrequestevent Source:" + sre.getsource ());
SYSTEM.OUT.PRINTLN ("Request Init");
}
}
The MyHttpServlet1 class accepts the request code:
[Java] View plain copy
</pre><pre name= "code" class= "Java" > @Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
SYSTEM.OUT.PRINTLN ("MyHttpServlet1 request Work");
<span style= "White-space:pre" > </span>system.out.println ("Current thread:" + thread.currentthread (). GetName ());
}
[Java] View plain copy
</pre><div>myhttpservlet class Accept request code: </div><pre name= "code" class= "java" ><pre name= "code" Class= "Java" > @Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
SYSTEM.OUT.PRINTLN ("Myhttpservlet request Work");
<span style= "White-space:pre" > </span>system.out.println ("Current thread:" + thread.currentthread (). GetName ());
}
Send a request output to Myhttpservlet as follows:

It can be seen that after receiving a request, the ServletRequest object is initialized first, the requestinitialized () method is called, and then a property substitution is made to enable asynchronous processing, after which the request is processed, and the request object is finally destroyed.
Send a request output to MyHttpServlet1 as follows:

The process of processing is the same as sending the request to the Myhttpservlet, but the processing thread that is seen to request is different.
Adding properties to the request and the listener for the property in ServletContext are similar:
[Java] View plain copy
Req.setattribute ("area", "zh");
Req.setattribute ("area", "TS");
Req.removeattribute ("area");
The output is as follows:

Property substitution is also the value returned before the replacement, and the substitution of the property in ServletContext is the same.


Related articles:
How is Threads allocated to handle Servlet request?
Java Serialization (i)
Httpsessionactivationlistener Example use case
Understanding the serialization of Java objects
Java Tomcat Implementation Session object persistence principle and Configuration method introduction
Using Sessions and Session persistence
Practical Usage of Httpsessionbindinglistener and Httpsessionattributelistener
What is difference between Httpsessionattributelistener and Httpsessionbindinglistener?

Using listeners in Java Web programs can be done in two ways

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.