3. Servlet listener and Servlet listener

Source: Internet
Author: User

3. Servlet listener and Servlet listener
Author: Zen Lou wangyue (http://www.cnblogs.com/yaoyinglong) 1. ServletConfig and ServletContext 1.1 ServletConfig and ServletContext configuration and use

Some information unrelated to the business logic should not be hard-coded into the program. Generally, it should be placed in ServletConfig or ServletContext.

Configure the ServletConfig and ServletContext parameters in the web. xml file:

<! -- Configure the ServletContext parameter --> <context-param> <param-name> email </param-name> <param-value> yaoyinglong@gmail.com </param-value> </context-param>
<Servlet> <servlet-name> Test </servlet-name> <servlet-class> com. yyl. Test </servlet-class> <! -- Configure the ServletConfig parameter --> <init-param> <param-name> email </param-name> <param-value> yaoyinglong@gmail.com </param-value> </init-param> </servlet>

We can clearly see that the parameter ServletConfig is configured inside the <servlet> node, while the parameter ServletContext is configured outside the <servlet> node.

Use the ServletConfig and ServletContext parameters:

String servletConfigEmail=getServletConfig().getInitParameter("email");String servletContextEmail=getServletContext().getInitParameter("email");

Needless to say, the value is only the parameter in that row.

Use range of the ServletConfig and ServletContext parameters:

ServletConfig parameters:

① It can only be available in the servlet configured with it;

② It is unavailable before the Java object is changed to Servlet (the init function has two versions, which are generally not overwritten and acceptedServletConfigThe version of the object, that is, overwrite and add super. init (ServletConfig )).

③ The ServletConfig parameter is read only once during Servlet initialization and cannot be modified midway through.

ServletContext is available for all servlets and JSP in Web applications.

1.2 examples of ServletConfig and ServletContext

These two objects are very important. When our program needs to read the configuration file, we can configure the path of the configuration file here, which is described in Spring configuration below:

If we use the Spring framework through MyEclipse, it will help us configure Spring. You do not need to do it yourself, but if you are using Eclipse, Sorry, it is not so considerate. We can only manually configure it ourselves. Whether it's for IDE or manually, we usually use Ctrl + C and Ctrl + V, but do you know how Spring works? Skip this step, or you canCheck if what I said is correct and point out the error (Thank you !!!)If you do not know, please follow me to see it:

First, let's see why Spring should be configured in web. xml:

When we do not configure Spring in web. xml, we do this when we want to obtain the configuration in Spring bean:

import org.springframework.beans.factory.BeanFactory;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {    public static void main(String[] args) {        BeanFactory beanFactory=new ClassPathXmlApplicationContext("appclicationContext.xml");        beanFactory.getBean("beanId");    }}

C/S can do this. What about B/S? We can use a Servlet to implement:

public void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml");    getServletContext().setAttribute("beanFactory", beanFactory);}

After this configuration, BeanFactory can be used in all JSP and Servlet of the Web application.

Another configuration method is the listener we will talk about below (you can check the listener content first ):

@Overridepublic void contextDestroyed(ServletContextEvent sce) {    BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml");    sce.getServletContext().setAttribute("beanFactory", beanFactory);}

Have you found that the Code is the same no matter how it is configured. Spring framework developers have also discovered this, so they have done it (they provide the last two implementations). We all know that, servlet and listener are both on the web. configured in xml. Therefore, our job is to configure the Servlet and listener for Spring framework developers to web. xml.

Note: Here I am just a simple description of the core part, the powerful Spring has to do more work than I have done here, and I will apply here. the path of the xml configuration file is hardcoded into the program. This is not good. We should use the ServletConfig and ServletContext parameters we are talking about to configure it in the xml file.

Let's see how Spring works:

Haha, I didn't lie to everyone. Spring has implemented Servlet and Listener Configuration Methods for us. However, in most cases, Listener is used for configuration. Let's go to this listener and see:

public class ContextLoaderListener implements ServletContextListener {    private ContextLoader contextLoader;    public void contextInitialized(ServletContextEvent event) {        this.contextLoader = createContextLoader();        this.contextLoader.initWebApplicationContext(event.getServletContext());    }    protected ContextLoader createContextLoader() {        return new ContextLoader();    }    public ContextLoader getContextLoader() {        return this.contextLoader;    }    public void contextDestroyed(ServletContextEvent event) {        if (this.contextLoader != null) {            this.contextLoader.closeWebApplicationContext(event.getServletContext());        }    }}

We found that when the Web application was started, he did two things: Create a ContextLoader class, and then call its initWebApplicationContext method to enter this method:

Public WebApplicationContext initWebApplicationContext (ServletContext servletContext) throws IllegalStateException, BeansException {// delete some parts that we do not care about for the moment because the length is too large ...... Try {// Determine parent for root web application context, if any. applicationContext parent = loadParentContext (servletContext); // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown.This. context =CreateWebApplicationContext (servletContext, parent); servletContext. setAttribute (WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this. Context );CurrentContextPerThread. put (Thread. currentThread (). getContextClassLoader (), this. context); // delete some of the parts that we do not care about for the moment because the length is too large ......
    }

We can clearly see from the rough code:WebApplicationContextObject, and then save itServletContextMedium (within the Application range ). Later, the Struts2 and Spring inheritance plug-ins can get BeanFactory from the Application and get the Actoin object in the Ioc container through BeanFactory, so that the Action dependency object will be injected.

Then I will trace it again.CreateWebApplicationContextFunction:

Protected WebApplicationContext createWebApplicationContext (ServletContext servletContext, ApplicationContext parent) throws BeansException {Class contextClass = determineContextClass (servletContext ......
ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils. instantiateClass (contextClass); wac. setParent (parent); wac. setServletContext (servletContext); // read the web. value in the <context-param> node in the xml fileWac. setConfigLocation (servletContext. getInitParameter (CONFIG_LOCATION_PARAM ));CustomizeContext (servletContext, wac); wac. refresh (); return wac ;}

The rough Code indicates that we must be in the web. configure the <context-param> parameter in the xml file. As for the configuration, we know that the value of the <param-value> parameter must be applicationContext. the path of the xml file. What is the parameter name? Later, it reads from that parameter, and we use the <param-name> value of the parameter group.

ViewCONFIG_LOCATION_PARAMConstant:

Therefore, the value of <param-name> is contextConfigLocation.

Ah!Didn't we talk about creating BeanFactory? Why is WebApplicationContext created here? It is traced and found that it inherits from BeanFactory. It mainly uses the getBean method of BeanFactory to obtain beans.

Now I understand the meaning of configuring Spring with listeners in web. xml.

How can we configure Servlet? (Leave a message if you don't understand it. It's not a waste of space here ).

1.3 ServletContext is NOT thread-safe

Each part of the application can access ServletContext. Therefore, if necessary, synchronize the following:

Synchronized (getServletContext () {// business logic code}
2. Listener (Listener)

The so-called listener is that when you do something, the other class pays attention to you and takes corresponding actions.

2.1 ServletContextListener

View the API and we can see that it listens to Web application initialization and Web application destruction actions, so we can instruct the listener to help us do what we want during Web application initialization and Web application destruction:

public class TestServletContextListener implements ServletContextListener {    @Override    public void contextDestroyed(ServletContextEvent sce) {        System.out.println("Oh,my god! I was killed");    }    @Override    public void contextInitialized(ServletContextEvent sce) {        System.out.println("houhou, God created me");        String email=sce.getServletContext().getInitParameter("email");        System.out.println("My Email is "+email);    }}

So that it can listen to our words? Not yet, because Tomcat will not let you monitor the initialization and destruction of Web applications if you implement the ServletContextListener interface. Tomcat only processes the tasks you configured in the web. xml file. Therefore, you need to configure the listener in web. xml:

Add under a node:

<listener>      <listener-class>com.yyl.TestServletContextListener</listener-class>  </listener>

Now the configuration is complete. The real-time users of ServletContextListener are used by me:

When I start Tomcat:

When we close Tomcat:

So far, do you have a question: how does Tomcat know that the com. yyl. TestServletContextListener you configured is used to listen to the creation and destruction actions of Web applications? That is, this listener is a ServletContext listener? Because Servlet has many other listeners (coming soon ). This is because the Web Container will check the class and check whether it inherits the listening interface or multiple listening interfaces to determine what type of events it listens.

3. Eight listener types (eight interfaces)

ServletContextAttributeListener: listens for adding, deleting, and replacing attributes in the ServletContext object.

HttpSessionListener: Listener for creating and destroying Web application sessions. Then you can know the number of concurrent users.

ServletRequestListener: listens to the Servlet action requested by the browser.

ServletRequestAttrubuteListener: Listener for adding, deleting, and replacing attributes in the request of the ServletRequest object.

HttpSessionBindingListener: the property itself is notified when it is added to or deleted from the session.

HttpSesionAttributeListener: Listener for adding, deleting, and replacing attributes in HttpSession.

ServletContextListener: listens to the Web application creation or revocation action.

HttpSessionActivationListener: When a Session is migrated to another JVM, it notifies you that the attributes of this interface are ready.

Today, I have no energy to give an example. next article!

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.