JavaEE Foundation (05): Filters, listeners, interceptors, application details

Keywords: Programming Attribute Session github xml

Source code for this article: GitHub. Click here || GitEE. Click here

1. Listener listener

1. Introduction to concepts

There are three components of JavaWeb: Servlet, Listener, Filter.A listener is a component that monitors the state changes of related objects in an application.

2. Event Source Object

Refers to the object being listened on.

  • ServletContext

ServletContextListener lifecycle monitoring, which has two methods, calling contextInitialized() at birth and contextDestroyed() at destruction;

The ServletContextAttributeListener property listens, which has three methods: adding attribute Added (), replacing attribute Replaced (), and removing attribute Removed ().

  • HttpSession

HttpSessionListener lifecycle monitoring: It has two methods: calling sessionCreated() at birth and sessionDestroyed() at destruction;

The HttpSessioniAttributeListener property listens on: It has three methods: adding attribute Added (), replacing attribute Replaced (), and removing attribute Removed ().

  • ServletRequest

ServletRequestListener lifecycle monitoring: It has two methods, requestInitialized() at birth and requestDestroyed() at destruction;

The ServletRequestAttributeListener property listens on: It has three methods: adding attribute Added (), replacing attribute Replaced (), and removing attribute Removed ().

3. Coding Cases

  • Related listeners

TheContextListener

public class TheContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Initialization: TheContextListener");
        ServletContext servletContext = servletContextEvent.getServletContext() ;
        servletContext.setAttribute("author","cicada");
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Destroy: TheContextListener");
    }
}

TheRequestListener

public class TheRequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("Initialization: TheRequestListener");
    }
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("Destroy: TheRequestListener");
    }
}

TheSessionListener

public class TheSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("Initialization: TheSessionListener");
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("Destroy: TheSessionListener");
    }
}

RequestAttributeListener

public class RequestAttributeListener implements ServletRequestAttributeListener {
    @Override
    public void attributeAdded(ServletRequestAttributeEvent evt) {
        System.out.println("Request Add attributes:"+evt.getName()+";"+evt.getValue());
    }
    @Override
    public void attributeRemoved(ServletRequestAttributeEvent evt) {
        System.out.println("Request Remove attributes:"+evt.getName()+";"+evt.getValue());
    }
    @Override
    public void attributeReplaced(ServletRequestAttributeEvent evt) {
        System.out.println("Request Replace attributes:"+evt.getName()+";"+evt.getValue());
    }
}
  • web.xml configuration file
<!-- Listener-related configurations -->
<listener>
    <listener-class>com.node05.servlet.listener.TheContextListener</listener-class>
</listener>
<listener>
    <listener-class>com.node05.servlet.listener.TheSessionListener</listener-class>
</listener>
<listener>
    <listener-class>com.node05.servlet.listener.TheRequestListener</listener-class>
</listener>
<listener>
    <listener-class>com.node05.servlet.listener.RequestAttributeListener</listener-class>
</listener>
<session-config>
    <!-- Set up session Failure time is 1 minute -->
    <session-timeout>1</session-timeout>
</session-config>
  • Test interface
public class ListenerServletImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 1. Get TheContextListener initialization data
        ServletContext servletContext = this.getServletContext() ;
        String author = String.valueOf(servletContext.getAttribute("author")) ;
        System.out.println("TheContextListener Author:"+author);
        // 2. Request property settings
        request.setAttribute("mood","smile");
        request.setAttribute("mood","agitated");
        // 3. Session creation, 1 minute expiration, call destroy
        HttpSession session = request.getSession(true) ;
        session.setAttribute("casually","casually");
        response.getWriter().print("Hello:Listener");
    }
}

2. Filter Filter

1. Introduction to filters

When a client requests a Servlet, the relevant Filter is executed first, and if the Filter passes, the Servlet that executes the request is inherited; if the Filter does not pass, the Servlet that the user requests is not executed.Filters can dynamically intercept requests and responses.

2. Filter interface

The Filter interface defines three core methods.

  • init()

When the application starts, the server instantiates the Filter object, calls its init method, reads the web.xml configuration, and completes the initial loading of the object.

  • doFilter()

The actual filtering operation, when the request reaches the server, the Servlet container will call the filter's doFilter method first.

  • destroy()

The container calls this method before destroying the filter, releasing the resources used by the filter.

3. Coding Cases

  • Write filters
public class ThePrintLogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String myName = filterConfig.getInitParameter("myName") ;
        System.out.println("myName: "+myName);
    }
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest ;
        HttpServletResponse response = (HttpServletResponse)servletResponse ;
        String name = request.getParameter("name") ;
        if (!name.equals("cicada")){
            response.getWriter().print("User Error !");
            return ;
        }
        chain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {
        System.out.println("ThePrintLogFilter destroy()");
    }
}
  • web.xml configuration file
<!-- Filter related configuration -->
<filter>
    <filter-name>thePrintLogFilter</filter-name>
    <filter-class>com.node05.servlet.filter.ThePrintLogFilter</filter-class>
    <init-param>
        <param-name>myName</param-name>
        <param-value>cicada</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>thePrintLogFilter</filter-name>
    <url-pattern>/filterServletImpl</url-pattern>
</filter-mapping>
  • Test interface
public class FilterServletImpl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("Hello:Filter");
    }
}

3. Interceptor Interceptor

The interceptor Interceptor in the Spring framework is similar to the filter Filter in the Servlet and is primarily used to intercept user requests and process them accordingly.For example, the interceptor can verify permissions, log requests, determine whether users are logged in, and so on.Request forwarding does not perform interception and filtering; redirection performs interception and filtering.

4. Source code address

GitHub·address
https://github.com/cicadasmile/java-base-parent
GitEE·address
https://gitee.com/cicadasmile/java-base-parent

Posted by mudasir on Tue, 17 Dec 2019 15:57:52 -0800