Article From:https://www.cnblogs.com/yangchongxing/p/9968483.html

【Java WebSpring MVC adds custom Servlet, Filter, Listener

 Reprinted: https://www.cnblogs.com/yangchongxing/p/9968483.html

Custom Servlet

package cn.ycx.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public MyServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("myservlet");
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

 

Custom Filter

package cn.ycx.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFilter implements Filter {
    public MyFilter() {
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("myfilter");
        chain.doFilter(request, response);
    }
    public void init(FilterConfig fConfig) throws ServletException {
    }
}

 

Custom Listener

package cn.ycx.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class MyServletRequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre)  { 
        System.out.println("requestDestroyed");
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre)  { 
        System.out.println("requestInitialized");
    }
}

 

Mode 1. Adding Web Application Initializer based on Java initializer (container supporting Servlet 3.0)

package cn.ycx.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;

import cn.ycx.filter.MyFilter;
import cn.ycx.listener.MyServletRequestAttributeListener;
import cn.ycx.listener.MyServletRequestListener;
import cn.ycx.servlet.MyServlet;

public class MyInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Custom Servlet
        ServletRegistration.Dynamic myServlet = servletContext.addServlet("myservlet", MyServlet.class);
        myServlet.addMapping("/myservlet");
        
        // Custom Filter
        FilterRegistration.Dynamic myFilter = servletContext.addFilter("myfilter", MyFilter.class);
        myFilter.addMappingForUrlPatterns(null, false, "/*");
        
        // Custom Listener
        servletContext.addListener(MyServletRequestListener.class);
        servletContext.addListener(MyServletRequestAttributeListener.class.getName());
    }
}

addServlet Overloading methods

public ServletRegistration.Dynamic addServlet(String servletName, String className);
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet);
public ServletRegistration.Dynamic addServlet(String servletName,Class <? extends Servlet> servletClass);

addFilter Overloading methods

public FilterRegistration.Dynamic addFilter(String filterName, String className);
public FilterRegistration.Dynamic addFilter(String filterName, Filter filter);
public FilterRegistration.Dynamic addFilter(String filterName,Class <? extends Filter> filterClass);

addListener Overloading methods

public void addListener(String className);
public <T extends EventListener> void addListener(T t);
public void addListener(Class <? extends EventListener> listenerClass);

 

Why is it possible to load custom classes by implementing this interface container?

Because in the Servlet 3.0 environment, the container looks up the class that implements the javax. servlet. Servlet Container Initializer interface in the classpath and configures the Servlet container with it. Spring providesThe implementation class of this interface is called SpringServletContainerInitializer, which finds the classes that implement the Web Application Initializer interface and assigns them tasks to complete.

SpringServletContainerInitializerClass source

@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
            throws ServletException {

        List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

        if (webAppInitializerClasses != null) {
            for (Class<?> waiClass : webAppInitializerClasses) {
                // Be defensive: Some servlet containers provide us with invalid classes,
                // no matter what @HandlesTypes says...
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((WebApplicationInitializer) waiClass.newInstance());
                    }
                    catch (Throwable ex) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
            return;
        }

        servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
        AnnotationAwareOrderComparator.sort(initializers);
        for (WebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);//Our custom Web Application Initializer class is executed here}
    }

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *