Servlet uses annotation Listener (Listener) and servletlistener

Source: Internet
Author: User

Servlet uses annotation Listener (Listener) and servletlistener

The @ WebListener annotation provided by Servlet3.0 defines a class that implements a specific listener interface as a listener.In this way, when we use listeners in web applications, we do not need to configure the listener description in the web. xml file.

Next we will create a listener and try to use the @ WebListener annotation to mark the listener, as shown below:

  

The listener code is as follows:

Package me. gacl. web. listener; import javax. servlet. servletContextEvent; import javax. servlet. servletContextListener; import javax. servlet. annotation. webListener;/*** use the @ WebListener annotation to mark the listener that implements the ServletContextListener interface as the listener */@ WebListenerpublic class implements ServletContextListener {@ Override public void contextDestroyed (ServletContextEvent sce) {System. out. println ("ServletContex destruction") ;}@ Override public void contextInitialized (ServletContextEvent sce) {System. out. println ("ServletContex initialization"); System. out. println (sce. getServletContext (). getServerInfo ());}}

  

The listener is initialized when the Web application starts, as shown in:

  

With the @ WebListener annotation, no configuration is required for our web. xml.

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  <display-name></display-name>      <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

The emergence of the Servlet3.0 specification allows us to develop Servlet, Filter, and Listener programs to achieve zero configuration in web. xml.

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.