JavaWeb three components (Servlet, Filter, Listener)

The three components of JavaWeb refer to: Servlet, Filter, and Listener. These three components provide different functions in JavaWeb development. 

The content of this blog refers to the following blogs: 

http://blog.csdn.net/gebitan505/article/details/70808730

http://blog.csdn.net/xiaojie119120/article/details/73274759

 

1、Servlet 

        Servlet is a dynamic resource used to process client requests, that is, when we type an address in the browser and press Enter to jump, the request will be sent to the corresponding Servlet for processing. The tasks of the servlet are:
  • Receiving request data: We all know that client requests will be encapsulated into HttpServletRequest objects, which contain various information such as request headers and parameters.
  • Handling requests: Usually we receive parameters in the service, doPost or doGet methods, and call the methods of the business layer (service) to process the request.
  • Complete the response: After processing the request, we generally forward or redirect to a certain page. Forwarding is a method in HttpServletRequest, and redirection is a method in HttpServletResponse. There is a big difference between the two.
      Forward (redirect) and redirect (forward):
forward方式:request.getRequestDispatcher("/somePage.jsp").forward(request, response);   
redirect方式:response.sendRedirect("/somePage.jsp");
  

    Forward is implemented through the forward(HttpServletRequest request, HttpServletResponse response) method of the RequestDispatcher object. The parameter of getRequestDispatcher() must start with "/", representing the root directory of the web application

When the forward action is executed, there must be no output to the client, otherwise an IllegalStateException will be thrown.

 

    Redirect is implemented by using the status code returned by the server. The server sets the status code through the setStatus(int status) method of HttpServletResponse. 301 represents permanent redirection, and 302 represents temporary redirection. HttpServletResponse encapsulates setStatus() and setHeader() methods into another method sendRedirect(String url).

 

     When using the forward form to jump, the address bar will display the servlet access address before the jump, because the jump is implemented on the server side and is transparent to the client browser. When redirection is used, the jump is implemented on the client side. In fact, the server is requested twice, the first time to obtain the redirected status code and address, and the second time to access the real address. 

 

     Creation of Servlet: Servlet can be created when the request is received for the first time, or it can be created when the server is started, which requires adding a configuration information < load-on-startup>5 in <servlet> of web.xml </load-on-startup>, when the value is 0 or greater than 0, it means that the container loads the servlet when the application starts. When it is a negative number or not specified, it indicates that the container loads the servlet when the servlet is requested. . 

 

     Servlet life cycle methods:

  • void init(ServletConfig) The initialization method of the servlet, which is only called once when the servlet instance is created. The servlet is a singleton, and the entire server only creates one servlet of the same type.
  • void service(ServletRequest,ServletResponse) The servlet's request processing method will be called immediately when the servlet is requested, and will be called once every time a request is processed. The ServletRequest class is the request class, and the ServletResponse class is the response class
  • void destroy() The method executed before the servlet is destroyed. It is only executed once to release the resources occupied by the servlet. Usually, the servlet has nothing to release, so this method is generally empty.
  • void doGet/doPost(HttpServletRequest, HttpServletResponse) 

    Other important methods of Servlet:

  • ServletConfig getServletConfig() The method of obtaining the configuration information of the servlet. The so-called configuration information is the information in the servlet tag in the web.xml under the WEB-INF directory
  • String getServletInfo() Get the information method of the servlet

    Servlet configuration:

    

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.briup.estore.web.servlet.LoginServlet</servlet-class>
</servlet>
  
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
  

 

  2、Filter 

  filter与servlet在很多的方面极其相似,但是也有不同,例如filter和servlet一样都又三个生命周期方法,同时他们在web.xml中的配置文件也是差不多的、 但是servlet主要负责处理请求,而filter主要负责拦截请求,和放行。 

 

filter四种拦截方式

  1. REQUEST:直接访问目标资源时执行过滤器。包括:在地址栏中直接访问、表单提交、超链接、重定向,只要在地址栏中可以看到目标资源的路径,就是REQUEST;
  2. FORWARD:转发访问执行过滤器。包括RequestDispatcher#forward()方法、< jsp:forward>标签都是转发访问;
  3. INCLUDE:包含访问执行过滤器。包括RequestDispatcher#include()方法、< jsp:include>标签都是包含访问;
  4. ERROR:当目标资源在web.xml中配置为< error-page>中时,并且真的出现了异常,转发到目标资源时,会执行过滤器。

    拦截方式配置:在<filter-mapping>中添加0~n个<dispatcher>子元素,来说明当前访问的拦截方式,默认拦截方式为REQUEST,一般REQUEST和FORWARD用的多一点,INCLUDE和ERROR用的少,示例配置如下: 

 

<filter-mapping>  
   <filter-name>myfilter</filter-name>  
   <url-pattern>/test.jsp</url-pattern>  
   <dispatcher>REQUEST</dispatcher>  
   <dispatcher>FORWARD</dispatcher>  
   <dispatcher>......</dispatcher>  
</filter-mapping>

 

   url-mapping的写法,匹配规则有三种:

  • 精确匹配 —— 如/foo.htm,只会匹配foo.htm这个URL
  • 路径匹配 —— 如/foo/*,会匹配以foo为前缀的URL
  • 后缀匹配 —— 如*.htm,会匹配所有以.htm为后缀的URL

    < url-pattern>的其他写法,如/foo/ ,/.htm ,/foo 都是不对的。

 

   执行filter的顺序 :如果有多个过滤器都匹配该请求,顺序决定于web.xml filter-mapping的顺序,在前面的先执行,后面的后执行 

   filter在web.xml中的配置如下:

   

<filter>
   <filter-name>filterDemo</filter-name>
   <filter-class>com.sjz.housekeeper.custom.FilterDemo</filter-class>
</filter> 
<filter-mapping>
   <filter-name>filterDemo</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping> 

 

3、Listener 

    Listener就是监听器,我们在JavaSE开发或者Android开发时,经常会给按钮加监听器,当点击这个按钮就会触发监听事件,调用onClick方法,本质是方法回调。在JavaWeb的Listener也是这么个原理,但是它监听的内容不同,它可以监听Application、Session、Request对象,当这些对象发生变化就会调用对应的监听方法。 

 

应用域监听: 

Ø ServletContext(监听Application)

  • 生命周期监听:ServletContextListener,它有两个方法,一个在出生时调用,一个在死亡时调用;

        void contextInitialized(ServletContextEvent sce):创建Servletcontext时

 

        void contextDestroyed(ServletContextEvent sce):销毁Servletcontext时

 

  • 属性监听:ServletContextAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。

       void attributeAdded(ServletContextAttributeEvent event):添加属性时;

 

        void attributeReplaced(ServletContextAttributeEvent event):替换属性时;

 

        void attributeRemoved(ServletContextAttributeEvent event):移除属性时;

 

Ø HttpSession(监听Session)

  • 生命周期监听:HttpSessionListener,它有两个方法,一个在出生时调用,一个在死亡时调用;

        voidsessionCreated(HttpSessionEvent se):创建session时

 

        void sessionDestroyed(HttpSessionEvent se):销毁session时

 

  • 属性监听:HttpSessioniAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。

        void attributeAdded(HttpSessionBindingEvent event):添加属性时;

 

        void attributeReplaced(HttpSessionBindingEvent event):替换属性时

 

        void attributeRemoved(HttpSessionBindingEvent event):移除属性时

 

Ø ServletRequest(监听Request)

  • 生命周期监听:ServletRequestListener,它有两个方法,一个在出生时调用,一个在死亡时调用;

         voidrequestInitialized(ServletRequestEvent sre):创建request时

 

         void requestDestroyed(ServletRequestEvent sre):销毁request时

 

  • 属性监听:ServletRequestAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。

        void attributeAdded(ServletRequestAttributeEvent srae):添加属性时

 

        void attributeReplaced(ServletRequestAttributeEvent srae):替换属性时

 

        void attributeRemoved(ServletRequestAttributeEvent srae):移除属性时

 

listener在web.xml中的配置:

 

<listener>
   <listener-class>com.sjz.housekeeper.custom.ListenerDemo</listener-class>
</listener>
  

 

    感知Session监听: 

  1. HttpSessionBindingListener监听 
  • 在需要监听的实体类实现HttpSessionBindingListener接口
  • 重写valueBound()方法,这方法是在当该实体类被放到Session中时,触发该方法 
  • 重写valueUnbound()方法,这方法是在当该实体类从Session中被移除时,触发该方法 
  1. HttpSessionActivationListener监听 
  • 在需要监听的实体类实现HttpSessionActivationListener接口 
  • 重写sessionWillPassivate()方法,这方法是在当该实体类被序列化时,触发该方法 
  • 重写sessionDidActivate()方法,这方法是在当该实体类被反序列化时,触发该方法 

   listener、filter、servlet的启动顺序为:listener->Filter->servlet,简单记为:理(Listener)发(Filter)师(servlet),执行的顺序不会因为三个标签在配置文件中的先后顺序而改变。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326208618&siteId=291194637