SpringMVC是如何控制试图层的?

首先,看一个SSM项目中的web.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
  <display-name>HelloSpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

<!--这里是编码过滤器,可要可不要-->
  <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>  
</filter>  
<filter-mapping>  
    <filter-name>CharacterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping>
 <!--这里是有关applicationContext.xml文件的配置,用于加载javaBean组件-->
  <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

<!--这个监听器是配合 上面的applicationContext.xml使用的-->
  <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

<!--这个servlet以及下面的servlet-mapping就是与视图控制相关的-->
  <servlet>
       <servlet-name>viewSpace</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
       <servlet-name>viewSpace</servlet-name>
       <url-pattern>*.form</url-pattern>
  </servlet-mapping>
</web-app>

一点补充的解释:

视图控制的配置还有另外一种写法:

<servlet>
        <servlet-name>chapter2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet-config.xml</param-value>
        </init-param>
    </servlet>

如果使用如上配置,Spring Web MVC框架将加载“classpath:spring-servlet-config.xml”来进行初始化上下文而不是“/WEB-INF/[servlet名字]-servlet.xml”。

可以看见,上面的一种写法对 viewSpace-servlet.xml的摆放位置是有所要求的,必须放在WEB-INF下面,并且名字必须符合[servlet名字]-servlet.xml。但是第二种方式就属于直接指定该xml文件所在位置,不用管这些规则。

猜你喜欢

转载自my.oschina.net/u/3442347/blog/1785368