网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

SpringMVC的web.xml配置详解

spring是目前最流行的框架。创建java web项目时,我们首先会遇到的配置文件就是web.xml,这是javaweb为我们封装的逻辑,不在今天的研究中。下面我们将简单讲讲web.xml中的配置。

创新互联建站专注于莫力达企业网站建设,响应式网站建设,成都商城网站开发。莫力达网站建设公司,为莫力达等地区提供建站服务。全流程按需设计,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务

一、一个空的web.xml

<?xml version="1.0" encoding="UTF-8"?>

二、标签介绍

web.xml中比较常见的标签以及其加载顺序为:

context-param > listener > filter > servlet

1、 Archetype Created Web Application

display-name 是标识项目的名称,这个不是很常用,可有可无的,或者说不需要我们去在意的东西。

2、


  webAppRootKey
  60000

context-param 是web.xml首先加载的标签,其下子标签有param-name和param-value.

此所设定的参数,在JSP网页中可以使用下列方法来取得:

${initParam.webAppRootKey}

若在Servlet可以使用下列方法来获得:

复制代码 代码如下:

String param_name=getServletContext().getInitParamter(“webAppRootKey”);

Spring MVC的web.xml配置详解

3、listener


    org.springframework.web.context.request.RequestContextListener

listenter在项目开始的时候就注入进来,尽在context-param之后,所以正常我们将spring配置在listener 中,这样方法spring 初始化相关的bean。

4、filter


    CharacterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
    
      forceEncoding
      true
    
  

  
    CharacterEncodingFilter
    /*
  

filter起到一个过滤的作用,在servlet执行前后,像上面的配置就是在过滤servlet前将编码转换UTF-8,filter-mapping 则是将filter和url路径进行映射。其中init-param则是将初始化需要的参数传入到filter-class中从而进行初始化。filter和filter-mapping中的name必须是相同的,才能起到映射的作用,而filter-mapping 中的url-pattern则是匹配请求路径的。上面‘/*'表示过滤所有请求的servlet,如果写成‘/zxh',则过滤http://localhost:8080/项目名/zxh这个请求。

5、servlet

   
     
    springMvc 
    org.springframework.web.servlet.DispatcherServlet 
       
         
        contextConfigLocation
        classpath:spring/spring-mvc.xml
       
     
    1 
  

  
  
    springMvc
    *.zxh
  

servlet和filter类似,需要先指定servlet对应的class类,然后将这个类和utl路径请求地址进行映射。这里不多说了。

以上就是web.xml文件中出现最多的几个标签。其他的比如:

6、欢迎页


    login.jsp
  

7、错误页

  
   
    java.lang.Throwable 
    /views/error.jsp 
   

  
   
    500 
    /views/500.jsp 
   

  
   
    404 
    /views/404.jsp 
  

三、示例

1、spring 框架解决字符串编码问题:过滤器 CharacterEncodingFilter(filter-name)

2、在web.xml配置监听器ContextLoaderListener(listener-class)
ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。

3、部署applicationContext的xml文件:contextConfigLocation(context-param下的param-name)

4、DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据某某规则分发到目标Controller(我们写的Action)来处理。

DispatcherServlet(servlet-name、servlet-class、init-param、param-name(contextConfigLocation)、param-value)
在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[servlet-name]-servlet.xml 的配置文件,生成文件中定义的bean

<?xml version="1.0" encoding="UTF-8"?> 
 

   
   
    characterEncodingFilter 
    org.springframework.web.filter.CharacterEncodingFilter 
     
      encoding 
      UTF-8 
     
     
      forceEncoding 
      true 
     
   
   
    characterEncodingFilter 
    /* 
   
   
   
   
   
    org.springframework.web.context.ContextLoaderListener 
   
   
   
   
    contextConfigLocation 
    classpath:spring/applicationContext.xml 
   

   
   
   
   
    default 
    *.css 
   
   
    default 
    *.swf 
   
   
    default 
    *.gif 
   
   
    default 
    *.jpg 
   
   
    default 
    *.png 
   
   
    default 
    *.js 
   
   
    default 
    *.html 
   
   
    default 
    *.xml 
   
   
    default 
    *.json 
   
   
    default 
    *.map 
   
   
   
   
    DispatcherServlet 
    org.springframework.web.servlet.DispatcherServlet 
     
     
      contextConfigLocation 
       
       
       
       
       
      classpath:spring/dispatcher-servlet.xml 
     
    1 
   
   
     
     
    DispatcherServlet 
     
     
     
    /  
   

   
    login.html 
   
    
    404 
    /nopage.html 
   
    
    java.lang.NullPointerException 
    /error.html 
   
   
    360 
   


四、spring加载

通过上面的了解,我们可以看出spring核心配置文件就是listener那块。在监听之前我们已经通过context-param将spring配置文件传到上下文中了(application)。下面我们就来看看spring是如何工作的吧

第一步:

点开listener源码,我们发现他有下面几个方法。和继承的关系。我们发现他实现了ContextLoaderListener这个接口,这个接口在参数设置好之后自动执行contextInitialized方法的。

Spring MVC的web.xml配置详解

那么我们来看看contextInitialized方法

Spring MVC的web.xml配置详解

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
      throw new IllegalStateException(
          "Cannot initialize context because there is already a root application context present - " +
          "check whether you have multiple ContextLoader* definitions in your web.xml!");
    }

    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring root WebApplicationContext");
    if (logger.isInfoEnabled()) {
      logger.info("Root WebApplicationContext: initialization started");
    }
    long startTime = System.currentTimeMillis();

    try {
      // Store context in local instance variable, to guarantee that
      // it is available on ServletContext shutdown.
      if (this.context == null) {
        this.context = createWebApplicationContext(servletContext);
      }
      if (this.context instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
        if (!cwac.isActive()) {
          // The context has not yet been refreshed -> provide services such as
          // setting the parent context, setting the application context id, etc
          if (cwac.getParent() == null) {
            // The context instance was injected without an explicit parent ->
            // determine parent for root web application context, if any.
            ApplicationContext parent = loadParentContext(servletContext);
            cwac.setParent(parent);
          }
          configureAndRefreshWebApplicationContext(cwac, servletContext);
        }
      }
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

      ClassLoader ccl = Thread.currentThread().getContextClassLoader();
      if (ccl == ContextLoader.class.getClassLoader()) {
        currentContext = this.context;
      }
      else if (ccl != null) {
        currentContextPerThread.put(ccl, this.context);
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
      }
      if (logger.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
      }

      return this.context;
    }
    catch (RuntimeException ex) {
      logger.error("Context initialization failed", ex);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
      throw ex;
    }
    catch (Error err) {
      logger.error("Context initialization failed", err);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
      throw err;
    }
  }

仔细研究官方解释,就是在这里初始化application,这里会用到contextClass+contextConfigLocation两个参数,如果contextClass在context-param提供了,我们就会根据这一个class去初始化application,很显然我们正常配置都没有配这个,而是配置了后者,配置了后者就会去根据contextConfigLocation中提供的配置文件去解析然后创建相关的bean和application操作,这个方法的最后会执行configureAndRefreshWebApplicationContext方法。这个方法就是在根据contextConfigLocation提供的配置文件中创建相关的bean。

五、springMVC 加载

springMVC其实和spring是一样的,但是他不用再程序开始时访问

   
     
    springMvc 
    org.springframework.web.servlet.DispatcherServlet 
       
         
        contextConfigLocation
        classpath:spring/spring-mvc.xml
       
     
    1 
  

  
  
    springMvc
    *.zxh
  

看DispatcherServlet源码中对contextConfigLocation参数的解释

Spring MVC的web.xml配置详解

上面明确指出我们这个参数给XmlWebApplicationContext类的,我们在进入XmlWebApplicationContext类看看究竟。

Spring MVC的web.xml配置详解

这样我们很容易理解为什么springmvc默认的配置文件会在WEB-INF/application.xml中的吧。

在dispatcherservlet中有一个初始化方法,这里就初始化配置中一些东西,比如说文件上传适配器的配置等等。

protected void initStrategies(ApplicationContext context) {
    initMultipartResolver(context);
    initLocaleResolver(context);
    initThemeResolver(context);
    initHandlerMappings(context);
    initHandlerAdapters(context);
    initHandlerExceptionResolvers(context);
    initRequestToViewNameTranslator(context);
    initViewResolvers(context);
    initFlashMapManager(context);
  }

总结

spring+springmvc在配置中主要就是上面的两个配置,当然spring的强大不是我们一两天能够研究来的,我上面只是简单的研究讨论了一下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


网页题目:SpringMVC的web.xml配置详解
新闻来源:http://bjjierui.cn/article/jjcdeg.html

其他资讯