web.xml中的配置,servlet,filter,listener的作用和原理

版权声明:转载请注明出处 https://blog.csdn.net/h2604396739/article/details/84899251

首先介绍servlet,filter和listen的原理:

servlet可以说是动态页面的基石,现在很多开发都是基于spring等各种框架,所以对servlet的了解可能少点,下面先用简单的例子,说明下servlet的作用

MyFirstServlet.java

class MyFirstServlet implements Servlet{

   //该函数用于初始化servelet就是把该servlet装载到内存中
   //该函数只会被调用一次
   public void init(ServletConfig config) throws ServletException{

   }

   //得到ServeletConfig对象
   public ServletConfig getServletConfig(){

      return null;
   }  

   //该函数是服务函数,我们的业务逻辑代码就是写在这里
   //该函数每次都会被调用
   public void service(ServletRequest request, ServletResponse response)

             throws ServletException, IOException{
   }

   //g该函数使得到servlet配置信息
   public String getServletInfo(){
      return null;
   }

   //销毁该servlet,从内存中清除掉,仅会被调用一次
   public void destroy(){

   }

}

     web中的配置如下

 <!--在这里声明servlet,并且给servlet起别名-->
    <servlet>
       <!--servlet-name是给该servlet指定名字-->
        <servlet-name>MyFirstServlet</servlet-name>
        <!--serlet-class要指明该Servlet放在哪个包下-->
        <servlet-class>com.hsm.MyFirstServlet</servlet-class>
    </servlet>

   <!--Servlet的映射-->
    <servlet-mapping>
         <!--这个servlet-name要和上面的servlet-name相同-->
        <servlet-name>MyFirstServlet</servlet-name>
        <!--URL-PATTERN这里就是将来访问该Servlet的资源名部分-->
        <url-pattern>/ABC</url-pattern>
    </servlet-mapping>

访问路径如下

http://localhost/*****/ABC

这里的ABC对应上面servlet-mapping中url-pattern的属性,所以最终请求会调用MyFirstServlet的service

 

Servlet中的过滤器Filter是实现了javax.servlet.Filter接口的服务器端程序,主要的用途是过滤字符编码、做一些业务逻辑判断等。其工作原理是,只要你在web.xml文件配置好要拦截的客户端请求,它都会帮你拦截到请求,此时你就可以对请求或响应(Request、Response)统一设置编码,简化操作;同时还可进行逻辑判断,如用户是否已经登陆、有没有权限访问该页面等等工作。它是随你的web应用启动而启动的,只初始化一次,以后就可以拦截相关请求,只有当你的web应用停止或重新部署的时候才销毁,以下通过过滤编码的代码示例来了解它的使用:

package com.hello.web.listener;
 
import java.io.IOException;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
// 主要目的:过滤字符编码;其次,做一些应用逻辑判断等.
// Filter跟web应用一起启动
// 当web应用重新启动或销毁时,Filter也被销毁
public class MyCharsetFilter implements Filter
{
	private FilterConfig config = null;
	
	public void destroy()
	{
		System.out.println("MyCharsetFilter准备销毁...");
	}
 
	public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain chain) throws IOException, ServletException
	{
		// 强制类型转换
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		// 获取web.xm设置的编码集,设置到Request、Response中
		request.setCharacterEncoding(config.getInitParameter("charset"));
		response.setContentType(config.getInitParameter("contentType"));
		response.setCharacterEncoding(config.getInitParameter("charset"));
		// 将请求转发到目的地
		chain.doFilter(request, response);
	}
 
	public void init(FilterConfig arg0) throws ServletException
	{
		this.config = arg0;
		System.out.println("MyCharsetFilter初始化...");
	}
}

以下是 MyCharsetFilter.java 在web.xml 中配置:

<filter>
      <filter-name>filter</filter-name>
      <filter-class>dc.gz.filters.MyCharsetFilter</filter-class>
      <init-param>
          <param-name>charset</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
      <init-param>
          <param-name>contentType</param-name>
          <param-value>text/html;charset=UTF-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>filter</filter-name>
      <!-- * 代表截获所有的请求  或指定请求,如/test.do  /xxx.do -->
      <url-pattern>/*</url-pattern>
  </filter-mapping>

以上的例子简单的说明了Filter的使用,具体其他的应用可以看具体的场景。

现在来说说Servlet的监听器Listener,它是实现了javax.servlet.ServletContextListener 接口的服务器端程序,它也是随web应用的启动而启动,只初始化一次,随web应用的停止而销毁。主要作用是: 做一些初始化的内容添加工作、设置一些基本的内容、比如一些参数或者是一些固定的对象等等。下面利用监听器对数据库连接池DataSource的初始化演示它的使用:

MyServletContextListener.java
package dc.gz.listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.dbcp.BasicDataSource;
 
/**
 * Web应用监听器
 */
public class MyServletContextListener implements ServletContextListener {
 
    // 应用监听器的销毁方法
    public void contextDestroyed(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        // 在整个web应用销毁之前调用,将所有应用空间所设置的内容清空
        sc.removeAttribute("dataSource");
        System.out.println("销毁工作完成...");
    }
 
    // 应用监听器的初始化方法
    public void contextInitialized(ServletContextEvent event) {
        // 通过这个事件可以获取整个应用的空间
        // 在整个web应用下面启动的时候做一些初始化的内容添加工作
        ServletContext sc = event.getServletContext();
        // 设置一些基本的内容;比如一些参数或者是一些固定的对象
        // 创建DataSource对象,连接池技术 dbcp
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("com.mysql.jdbc.Driver");
        bds.setUrl("jdbc:mysql://localhost:3306/hibernate");
        bds.setUsername("root");
        bds.setPassword("root");
        bds.setMaxActive(10);//最大连接数
        bds.setMaxIdle(5);//最大管理数
        //bds.setMaxWait(maxWait); 最大等待时间
        // 把 DataSource 放入ServletContext空间中,
        // 供整个web应用的使用(获取数据库连接)
        sc.setAttribute("dataSource", bds);
        System.out.println("应用监听器初始化工作完成...");
        System.out.println("已经创建DataSource...");
    }
}

web.xml中配置如下,很简单:

<!-- 配置应用监听器  -->
<listener>
	<listener-class>dc.gz.listeners.MyServletContextListener</listener-class>
</listener>

通过如下方式可以获取datasource

        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();
        servletContext.getAttribute("dataSource");
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();

有了上面的铺垫,更容易理解spring中web.xml所包含的配置和作用

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  

    <!-- 在Spring框架中是如何解决从页面传来的字符串的编码问题的呢?
    下面我们来看看Spring框架给我们提供过滤器CharacterEncodingFilter  
     这个过滤器就是针对于每次浏览器请求进行过滤的,然后再其之上添加了父类没有的功能即处理字符编码。  
      其中encoding用来设置编码格式,forceEncoding用来设置是否理会
 request.getCharacterEncoding()方法,设置为true则强制覆盖之前的编码格式。-->  
    <filter>  
        <filter-name>characterEncodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <!-- 项目中使用Spring 时,applicationContext.xml配置文件中并没有BeanFactory,要想在业
务层中的class 文件中直接引用Spring容器管理的bean可通过以下方式-->  
    <!--1、在web.xml配置监听器ContextLoaderListener-->  
    <!--ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为
它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
使用servletContextListener接口,开发者能够在为客户端请求提供服务之前向servletContext中添任何对象,
这个对象在servletcontxxt启动的时候被初始化,然后在ervletContext的整个运行期间都是可见的。
    在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。  
    它的API说明  
    第一段说明ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。  
    如果查看ContextLoaderServlet的API,可以看到它也关联了ContextLoader这个类而且它实现了HttpServlet这个接口  
    第二段,ContextLoader创建的是 XmlWebApplicationContext这样一个类,它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->  
    BeanFactory这样一来spring中的所有bean都由这个类来创建  
     IUploaddatafileManager uploadmanager = (IUploaddatafileManager)    ContextLoaderListener.getCurrentWebApplicationContext().getBean("uploadManager");
     -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!--2、部署applicationContext的xml文件-->  
    <!--如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,  
    在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。  
    如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:  
    在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并以“,”号分隔。  
    也可以这样applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,  
    applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。  
    在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。-->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring/applicationContext.xml</param-value>  
    </context-param>  

    <!--如果你的DispatcherServlet拦截"/",为了实现REST风格,拦截了所有的请求,那么同时对*.js,*.jpg等静态文件的访问也就被拦截了。-->  
    <!--方案一:激活Tomcat的defaultServlet来处理静态文件-->  
    <!--要写在DispatcherServlet的前面, 让 defaultServlet先拦截请求,这样请求就不会进入Spring了,我想性能是最好的吧。-->  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.css</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.swf</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.gif</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.jpg</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.png</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.js</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.html</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.xml</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.json</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>*.map</url-pattern>  
    </servlet-mapping>  
    <!--使用Spring MVC,配置DispatcherServlet是第一步。DispatcherServlet是一个Servlet,,所以可以配置多个DispatcherServlet-->  
    <!--DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据某某规则分发到目标Controller(我们写的Action)来处理。-->  
    <servlet>  
        <servlet-name>DispatcherServlet</servlet-name><!--在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[servlet-name]-servlet.xml 的配置文件,生成文件中定义的bean。-->  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <!--指明了配置文件的文件名,不使用默认配置文件名,而使用dispatcher-servlet.xml配置文件。-->  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <!--其中<param-value>**.xml</param-value> 这里可以使用多种写法-->  
            <!--1、不写,使用默认值:/WEB-INF/<servlet-name>-servlet.xml-->  
            <!--2、<param-value>/WEB-INF/classes/dispatcher-servlet.xml</param-value>-->  
            <!--3、<param-value>classpath*:dispatcher-servlet.xml</param-value>-->  
            <!--4、多个值用逗号分隔-->  
            <param-value>classpath:spring/dispatcher-servlet.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup><!--是启动顺序,让这个Servlet随Servletp容器一起启动。-->  
    </servlet>  
    <servlet-mapping>  
        <!--这个Servlet的名字是dispatcher,可以有多个DispatcherServlet,是通过名字来区分的。每一个DispatcherServlet有自己的WebApplicationContext上下文对象。同时保存的ServletContext中和Request对象中.-->  
        <!--ApplicationContext是Spring的核心,Context我们通常解释为上下文环境,我想用“容器”来表述它更容易理解一些,ApplicationContext则是“应用的容器”了:P,Spring把Bean放在这个容器中,在需要的时候,用getBean方法取出-->  
        <servlet-name>DispatcherServlet</servlet-name>  
        <!--Servlet拦截匹配规则可以自已定义,当映射为@RequestMapping("/user/add")时,为例,拦截哪种URL合适?-->  
        <!--1、拦截*.do、*.htm, 例如:/user/add.do,这是最传统的方式,最简单也最实用。不会导致静态文件(jpg,js,css)被拦截。-->  
        <!--2、拦截/,例如:/user/add,可以实现现在很流行的REST风格。很多互联网类型的应用很喜欢这种风格的URL。弊端:会导致静态文件(jpg,js,css)被拦截后不能正常显示。 -->  
        <url-pattern>/</url-pattern> <!--会拦截URL中带“/”的请求。-->  
    </servlet-mapping>  

    <welcome-file-list><!--指定欢迎页面-->  
        <welcome-file>login.html</welcome-file>  
    </welcome-file-list>  
    <error-page> <!--当系统出现404错误,跳转到页面nopage.html-->  
        <error-code>404</error-code>  
        <location>/nopage.html</location>  
    </error-page>  
    <error-page> <!--当系统出现java.lang.NullPointerException,跳转到页面error.html-->  
        <exception-type>java.lang.NullPointerException</exception-type>  
        <location>/error.html</location>  
    </error-page>  
    <session-config><!--会话超时配置,单位分钟-->  
        <session-timeout>360</session-timeout>  
    </session-config>  
</web-app>

借鉴:

https://www.cnblogs.com/wkrbky/p/5929943.html

https://blog.csdn.net/pg_guo/article/details/9118633

猜你喜欢

转载自blog.csdn.net/h2604396739/article/details/84899251