Java Web-based Listener: monitor each action of a Servlet

Source: Internet
Author: User

Java Web-based Listener: monitor each action of a Servlet

I have learned a lot about servlet before. In this summary, let's talk about the listener. When talking about the listener, it is no stranger to desktop programs and mobile apps. The common routine is to drag a control, then, you can bind a listener to the listener to listen to the event of the object for response. Essentially, these are the specific implementation of the observer mode, and the listener in the web program is no exception.

To use listeners in Java Web programs, you can use either of the following methods:

The annotation @ WebListener is used to identify a custom listener;

 

@WebListenerpublic class CustomListener implements Listener {}
Use listeners by configuring in web. xml;
 
  
   org.springframework.web.context.ContextLoaderListener
  
 

 

In Java Web programs, it mainly supports three objects: ServletContext, HttpSession, and ServletRequest.

1. The ServletContext listener has two types of listeners used to listen to the ServletContext object: ServletContextListener: This listener is used to listen to the initialization and destruction events of the ServletContext; ServletContextAttributeListener: this listener is used to listen for deletion, addition, and replacement events of attributes in ServletContext. The instance is as follows:
@WebListenerpublic class MyServletListener implements ServletContextListener, ServletContextAttributeListener {public void contextInitialized(ServletContextEvent sce) {System.out.println("ServletContextEvent source: " + sce.getSource());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("attribute added:  " + event.getName() + "--" + event.getValue());}public void attributeRemoved(ServletContextAttributeEvent event) {System.out.println("ServletContextAttributeEvent source: " + event.getSource());System.out.println("attribute removed:  "+ event.getName() + "--" + event.getValue());}public void attributeReplaced(ServletContextAttributeEvent event) {System.out.println("ServletContextAttributeEvent source: " + event.getSource());System.out.println("attribute replaced:  "+ event.getName() + "--" + event.getValue());}}
This class implements the above two interfaces, starts the Servlet container, analyzes the results, and outputs the following: we can see that the ServletContext is created first during the startup process, which inspires the contextInitialized listener method, then, the init () method of each Servlet is called to initialize each Servlet and initialize all the servlets (here there are two custom Servlets, MyServlet and TestServlet) after initialization, an attribute is added to the ServletContext. Both the event object and the added attribute are provided by the Servlet container. When the Servlet container is closed, the analysis result is as follows: the destroy method of all servlets will be called first, and then the ServletContext instance will be destroyed. When adding, replacing, or deleting attributes, the listener is called. The Code is as follows:
ServletContext context = req.getServletContext();context.setAttribute("country", "zn");context.setAttribute("country", "en");context.removeAttribute("country");
Code output: note that setAttribute () is used when the attribute is replaced, except that the key value is the same. When the property is replaced, the listener obtains the old value (I think the old value and new value should provide the corresponding API ). 2. HttpSession listeners have four types of listeners used to listen to HttpSession objects: HttpSessionListener: used to listen to the creation and destruction of HttpSession; HttpSessionActivationListener: This listener is used in a distributed environment, this class is used when an HttpSession instance needs to be migrated or serialized between different virtual machines, when an HttpSession object is migrated to a new virtual machine or deserialized, The sessionDidActivate () method is called. When an HttpSession instance moves out of or serializes the old virtual machine, sessionWillPassivate () is called () method; HttpSessionAttributeListener: used to listen to the deletion, addition, and replacement events of attributes in HttpSession. HttpSessionBindingListener: in fact, there is a Ses in the new Servlet3.1 specification. Sion listener, javax. servlet. http. httpSessionIdListener is used to listen for changes to SessionId. Because Tomcat 7 does not support Servlet3.1, this class cannot be found, so it is not written here. If you are interested, try it yourself. 1. HttpSessionListener and HttpSessionAttributeListener:
@WebListenerpublic class MyHttpSessionListener implements HttpSessionListener, HttpSessionAttributeListener {private Long startTime;public void attributeAdded(HttpSessionBindingEvent event) {startTime = (Long) event.getSession().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:
@WebServlet(name="myHttpSessionServlet", urlPatterns="/myHttpSessionServlet", loadOnStartup=1)public class MyHttpSessionServlet extends HttpServlet {private static final long serialVersionUID = 5687825632187950599L;@Overrideprotected 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");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}}
When you request resources of the website for the first time, the output is as follows: You can see that the first time you create an HttpSession, you call the sessionCreated () method. The corresponding property listener is triggered when the method is added, and the value before the replacement is returned when the property is replaced.
After the survival time is set, the method of Session destruction will be triggered. The output is as follows: it can be seen that Session destruction does not only call the sessionDestroyed () method. After this method is executed, the attributeRemoved () method is also called to clear all the attributes saved in it. 2. HttpSessionActivationListener the listener works in a distributed environment or when a sequence of HttpSession instances is required. Because sessions are stored in the memory, sometimes the server persistently stores sessions with less access to the storage device to save memory, including the file system and database, in this way, the memory space can be saved, and on the other hand, it also tells us not to put too much data in the Session to avoid the burden on the server. In a distributed environment, if a machine is down and cannot be accessed, You Can serialize the Session and transmit it to the JVM of another server. This requires that the data stored in the Session be serializable, this listener will be used at this time; serialization of sessions is generally performed by Servlet containers, We can configure; ERROR:
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 an incorrect method of use. HttpSession cannot be serialized. serialization here only converts the information in the Session instance to the data format transmitted in the network. The meaning scope must be greater than the serialization concept in Java, the general understanding is to convert an object into a string. As for the serialization of sessions, this is obvious. If the server goes down, all the information of the client accessing the server will be lost because it exists in the memory, after the Session is serialized to the storage device, the user information can be restored after the server resumes operation.
3. HttpSessionBindingListener first, this listener is similar to the previous HttpSessionAttributeListener, but they have the following differences: HttpSessionAttributeListener must be registered, or annotated or web. xml, which is used to listen to all Session instances in the entire application. It corresponds to the attributes of all Session instances and belongs to a common listener; httpSessionBindingListener is tailored for a specific Session and a listener with a specific attribute, and does not need to be registered. The following example is used:
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;}@Overridepublic 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");}
Add attributes to the Session in the doGet () method:
session.setAttribute("person", new Person("lmy", 23));session.setMaxInactiveInterval(10);
After the request is sent, the output is as follows:
HttpSessionBindingEvent source: org.apache.catalina.session.StandardSessionFacade@fdfaab5person bound
After 10 seconds, the Session becomes invalid and the output is:
HttpSessionBindingEvent source: org.apache.catalina.session.StandardSessionFacade@fdfaab5person unbound
3. ServletRequest listeners have three types of listeners used to listen to ServletRequest objects: ServletRequestListener: used to listen to creation and destruction of ServletRequest. Note that Servlet containers reuse ServletRequest through pools, to create a ServletRequest instance is to retrieve an instance from the pool and destroy this object, that is, to put the instance back into the pool. ServletRequestAttributeListener is used to listen to the deletion, addition, and replacement events of attributes in ServletRequest. AsyncListener: the listener code is as follows:
@WebListenerpublic 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");}}
Request Code for the MyHttpServlet1 class:

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("MyHttpServlet1 request work");System.out.println("current thread :" + Thread.currentThread().getName());}
Request Code for the MyHttpServlet class: 

@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("MyHttpServlet request work");  System.out.println("current thread :" + Thread.currentThread().getName()); }
Send a request to MyHttpServlet with the following output: it can be seen that after receiving a request, initialize the ServletRequest object, call the requestInitialized () method, and then you will find Replaced attributes to enable asynchronous ProcessingAnd then process the request, and finally destroy the request object. The process for sending a request to MyHttpServlet1 is the same as that for sending a request to MyHttpServlet. Processing threads are different.. Adding a property in the request process is similar to the property listener in ServletContext: 
req.setAttribute("area", "zh");req.setAttribute("area", "ts");req.removeAttribute("area");
The output is as follows: the value before replacement is returned when the attribute is replaced, which is the same as that in ServletContext.

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.