JavaEE base (05): filter, listener, interceptors, Detailed application

This article Source: GitHub · Click here || GitEE · Click here

A, Listener Listener

1, the concept Introduction

JavaWeb three major components: Servlet, Listener, Filter. Listener listens component refers to the relevant object state changes in the application.

2, event source object

It refers to the object being monitored.

  • ServletContext

ServletContextListenerLifecycle listener, it has two methods, calling at birth contextInitialized(), called when the destruction contextDestroyed();

ServletContextAttributeListenerProperty monitor, it has three methods, add properties attributeAdded(), the replacement property attributeReplaced(), when the property is removed attributeRemoved().

  • HttpSession

HttpSessionListenerLifecycle listener: it has two methods, calling at birth sessionCreated(), called when the destruction sessionDestroyed();

HttpSessioniAttributeListenerProperty monitor: It has three methods, add properties attributeAdded(), property replacement attributeReplaced(), removal of property attributeRemoved().

  • ServletRequest

ServletRequestListenerLifecycle listener: it has two methods, calling at birth requestInitialized(), called when the destruction requestDestroyed();

ServletRequestAttributeListenerProperty monitor: It has three methods, add properties attributeAdded(), property replacement attributeReplaced(), removal of property attributeRemoved().

3, coding Case

  • Related listeners

TheContextListener

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

TheRequestListener

public class TheRequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("初始化:TheRequestListener");
    }
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("销毁:TheRequestListener");
    }
}

TheSessionListener

public class TheSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("初始化:TheSessionListener");
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("销毁:TheSessionListener");
    }
}

RequestAttributeListener

public class RequestAttributeListener implements ServletRequestAttributeListener {
    @Override
    public void attributeAdded(ServletRequestAttributeEvent evt) {
        System.out.println("Request添加属性:"+evt.getName()+";"+evt.getValue());
    }
    @Override
    public void attributeRemoved(ServletRequestAttributeEvent evt) {
        System.out.println("Request移除属性:"+evt.getName()+";"+evt.getValue());
    }
    @Override
    public void attributeReplaced(ServletRequestAttributeEvent evt) {
        System.out.println("Request替换属性:"+evt.getName()+";"+evt.getValue());
    }
}
  • web.xml configuration file
<!-- 监听器相关配置 -->
<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>
    <!-- 设置session失效时间为1分钟 -->
    <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、获取TheContextListener初始化数据
        ServletContext servletContext = this.getServletContext() ;
        String author = String.valueOf(servletContext.getAttribute("author")) ;
        System.out.println("TheContextListener Author:"+author);
        // 2、Request属性设置
        request.setAttribute("mood","smile");
        request.setAttribute("mood","agitated");
        // 3、Session创建,1分钟失效,调用销毁
        HttpSession session = request.getSession(true) ;
        session.setAttribute("casually","casually");
        response.getWriter().print("Hello:Listener");
    }
}

Two, Filter filter

1, filter Introduction

When a client requests Servlet, the first implementation of the relevant Filter, Filter, if passed, inheritance Servlet execution of the request; if Filter is not passed, it will not perform Servlet requested by the user. The filter may dynamically intercept requests and responses.

2, Filter Interface

Filter interface defines three core methods.

  • init()

When the application starts, the server instance of Filter object and calls the init method thereof, read web.xml configuration, the object initialization is completed loading.

  • doFilter()

The actual filtration operation, a request reaches the server, Servlet container will first call the method doFilter filter.

  • destroy()

The container invokes this method before the destruction of the filter, the filter release resources occupied.

3, coding Case

  • Writing 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>
    <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");
    }
}

Three, Interceptor interceptor

Spring Framework interceptor Interceptor similar filter Filter Servlet is used primarily to intercept the user request and the corresponding treatment. For example permissions may be verified by the interceptor, the log recording request information, determines whether the user login and the like. Intercept request forwarding is not executed, filtered; redirection execution block and filter.

Fourth, the source address

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

Guess you like

Origin www.cnblogs.com/cicada-smile/p/12057924.html