具体分析applicationContext.xml和spring3-servlet.xml

本文详细介绍了Spring MVC的工作原理及配置方式,包括web.xml的加载顺序、Spring配置文件的加载流程、DispatcherServlet的配置、静态资源处理、视图解析器配置等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 首先看一下web.xml,通过查看log4j的日志可以发现在服务器启动时applicationContext.xml是先于spring3-servlet.xml加载,因此applicationContext.xml中已经注册到BeanFactory的bean在spring3-servlet.xml也是可以使用的,比如在applicationContext.xml中通过context:component-scan扫描了service和dao包,而在spring3-servlet.xml只扫描了web包,但web包中的Controller依然被注入了Service。
  • web.xml各个标签的加载顺序:context-param -> listener -> filter -> servlet
<?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_2_5.xsd"
    version="2.5">
    <!-- 初始化Spring容器并加载Spring配置文件applicationContext.xml,默认在WebRoot/WEB-INF目录下面 ,可以通过<context-param>的contextConfigLocation属性指定路径-->
    <!-- <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-   value>classpath:com/lince/config/applicationContext.xml</param-value>
    </context-param> -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 使用filter来统一字符编码 -->
    <filter>
        <filter-name>Set Character Encoding</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>Set Character Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 加载DispatcherServlet并加载其的配置文件spring3-servlet.xml,默认也是在WEB-INF目录下 -->
    <servlet>
        <servlet-name>spring3</servlet-name>        <!-- 默认找到的是spring3-servlet.xml -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:com/lince/config/spring3-servlet.xml</param-value>
        </init-param> -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring3</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- <servlet-mapping>
        <servlet-name>spring3</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>   -->    <!-- 通过这个过滤,可以在webroot下直接访问html -->

    <welcome-file-list>
        <!-- <welcome-file>login.html</welcome-file> -->
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation=" 
          http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
          http://www.springframework.org/schema/tx 
          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context-3.0.xsd 
          http://www.springframework.org/schema/aop 
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    default-autowire="byName">
    <!-- 注意上面的default-autowire="byName",如果没有这个声明那么HibernateDaoSupport中的sessionFactory不会被注入 -->
    <!-- 约定优于配置-->

    <!-- 自动扫描组件,包括@Controller,@Service,@Repository这里要把web下面的 controller去除,他们已经在spring3-servlet.xml中配置了,也就是已经加入beanFactory,否则会影响注入 -->
    <!-- 还发现了一个问题,就是如果不扫描@Repository,页面都进不去,报404,后来发现是这里的default-autowire和Javabean中@Autowire有冲突。。但最后还是要扫描@Repository,因为要给DAO注入sessionFactory -->
    <context:component-scan base-package="com.lince">
        <context:exclude-filter type="regex"
            expression="com.lince.web.*" />
    </context:component-scan>
    <!-- <context:component-scan base-package="com.lince.service.impl">
    </context:component-scan>
    <context:component-scan base-package="com.lince.dao.impl">
    </context:component-scan> -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url"
            value="jdbc:mysql://127.0.0.1:3306/ytcdb2?useUnicode=true&amp;characterEncoding=UTF-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <!-- 为了不用每次都去数据库,可以在这里配置连接池,当然,还要引入响应的jar包 -->
        <!-- <property name="maxActive" value="10"></property>
        <property name="maxWait" value="60000"></property>
        <property name="maxIdle" value="5"></property> -->
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- 由于通过autowire启用了自动装载,所以下面的这个dataSource其实是可以不用写的 ,后面通过ref引用的都是一样的道理-->
        <property name="dataSource" ref="dataSource" />
        <property name="mappingDirectoryLocations">
            <list><!-- 这里直接映射的pojo类所在的包,简单方便不用每次加一个pojo类都需要到这里来添加 -->
                <value>classpath:com/lince/model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">
                    true
                </prop>
                <!-- <prop key="hibernate.connection.autocommit">true</prop> -->
            </props>
        </property>
    </bean>

    <!-- 下面是配置声明式事务管理的,个人感觉比用注解管理事务要简单方便 -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <aop:config>
    <!-- advisor包含一个切点和一个通知,而aspect包含多个 -->
        <aop:advisor pointcut="execution(* com.lince.service.*Service.*(..))"
            advice-ref="txAdvice" />
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
        <!-- Service类中以get*,query*等等开头的查询操作只能执行只读事务;对于所有的事务,如果出现异常就回滚 -->
            <tx:method name="get*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <tx:method name="*" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>


</beans>
  • spring3-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation=" 
           http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/mvc 
           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
    default-autowire="byName">  <!-- default-autowire="byName",约定优于配置 -->
    <!--mvc:annotation-driven注册了 RequestMappingHandlerMapping, a RequestMappingHandlerAdapter,and an ExceptionHandlerExceptionResolver 
        能启动@RequestMapping,@ExceptionHandler, and others注释 -->
    <mvc:annotation-driven />
    <!-- 把无法mapping到Controller的path交给default servlet handler处理 -->
    <mvc:default-servlet-handler />
    <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理而由前面的default-servlet-handler处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->
    <mvc:resources mapping="/img/**" location="/img/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/html/**" location="/html/" />

    <!-- ①:对web包中的Controller类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <!-- 也就是说这里相当于实例化了Controller类并且给它注入了Service的实例?它没有扫描Service的包诶。。 -->
    <!-- 因为applicationContext.xml先于本文件加载,所以那边先进行扫描,其实是注入了的,byName通过@Service(...)里面的值进行匹配 -->
    <context:component-scan base-package="com.lince.web" />

    <!--- StringHttpMessageConverter bean -->

    <!-- 下面这两个处理器映射默认跟<mvc:annotation-driven />功能几乎是一样的,都能够启用SpringMVC的注解功能,只是如果要添加一些其它功能的时候就进行配置了 -->
    <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射,添加拦截器,类级别的处理器映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <list>
            <!-- 用于检查session是否存在 -->
                <bean class="com.lince.util.MyHandlerInterceptor" />
            </list>
        </property>
    </bean>

    <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射,对有RequestMapping注解的控制器进行HTTP路径、HTTP方法和请求参数解析,
        这里 配置了一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0" />
        <!-- cacheSeconds =0时,则将设置如下响应头数据: 
        Pragma:no-cache     HTTP 1.0的不缓存响应头
        Expires:1L          useExpiresHeader=true时,HTTP 1.0 
        Cache-Control :no-cache  useCacheControlHeader=true时,HTTP 1.1 
        Cache-Control :no-store  useCacheControlNoStore=true时,该设置是防止Firefox缓存 -->
        <property name="webBindingInitializer">
            <bean class="com.lince.util.MyWebBinding" />
        </property>
        <!-- 配置一下对json数据的转换 -->
        <property name="messageConverters">
            <list>
                <!-- 对@ResponseBody注释的方法生效 -->
                <bean
                    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter" />
            </list>
        </property>
    </bean>

    <!-- 配置对JSP文件的视图解析器 -->
    <bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/view/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolverJsp"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
        <property name="viewClass"
            value="org.springframework.web.servlet.view.InternalResourceView" />
        <property name="order" value="1" />
    </bean>
    <!-- 配置对HTML文件的视图解析器 -->
    <!-- 设置freeMarker的配置文件路径 -->
    <bean id="freemarkerConfiguration"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView
            </value>
        </property>
        <property name="cache">
            <value>true</value>
        </property>
        <!-- <property name="allowSessionOverride" value="true" /> -->
        <property name="suffix">
            <value>.html</value>
        </property>
        <!-- <property name="viewNames" value="*.html,*.jsp" /> -->
        <property name="contentType">
            <value>text/html; charset=UTF-8</value>
        </property>
        <property name="order" value="0" />
    </bean>


</beans> 
### SSM框架中的配置文件及其关系 #### 1. **web.xml** `web.xml` 是 Java Web 应用程序的部署描述符,用于定义应用程序的整体结构初始化参数。它是整个项目的入口点。 - 定义 `DispatcherServlet` 的映射路径,负责拦截所有 HTTP 请求并将它们转发到 Spring MVC 控制器。 - 配置监听器(Listener),例如 `ContextLoaderListener`,用于加载全局上下文 `applicationContext.xml` 或其他类似的 XML 文件。 - 设置过滤器(Filter),如字符编码过滤器,确保请求响应的编码一致性。 ```xml <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` 此部分通过 `ContextLoaderListener` 初始化全局上下文,并由 `DispatcherServlet` 加载特定于 Spring MVC 的配置[^1]。 --- #### 2. **spring-mybatis.xml** 该文件主要用于 MyBatis Spring 的集成,配置数据源、事务管理器以及 SQL Session 工厂。 - 数据源 (`DataSource`) 使用第三方库(如 Druid、C3P0)实现数据库连接池。 - 配置事务管理器 (`TransactionManager`) 来管理事务。 - 创建 `SqlSessionFactory` 并将其与 MyBatis 映射文件关联。 ```xml <!-- 数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!-- Mapper 扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper" /> </bean> ``` 此部分实现了 MyBatis Spring 的无缝集成,使得 DAO 层可以通过注解或接口方式访问数据库[^2]。 --- #### 3. **spring-mvc.xml** 这是 Spring MVC 的核心配置文件,主要关注前端控制器的行为视图解析。 - 组件扫描仅限于 Controller 类型的 Bean。 - 配置视图解析器以指定 JSP 页面的位置扩展名。 - 启用对静态资源的支持以及其他高级功能。 ```xml <context:component-scan base-package="com.ssm.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <mvc:default-servlet-handler/> <mvc:annotation-driven/> ``` 这部分专注于处理用户的请求并返回相应的视图[^1]。 --- #### 4. **mybatis-config.xml** MyBatis 的核心配置文件,通常包含通用设置插件声明。 - 配置缓存机制。 - 指定日志记录工具。 - 添加自定义类型处理器或其他扩展组件。 ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 缓存设置 --> <settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> </settings> <!-- 日志记录 --> <typeAliases> <package name="com.example.model"/> </typeAliases> <!-- 插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"/> </plugins> </configuration> ``` 此文件提供了 MyBatis 运行所需的底层支持,而具体的 SQL 映射则交由单独的 Mapper 文件完成[^3]。 --- #### 配置关系总结 1. **web.xml** 负责启动容器并加载全局上下文 DispatcherServlet。 2. **spring-mybatis.xml** 提供了持久层所需的数据源、事务管理会话工厂。 3. **spring-mvc.xml** 处理业务逻辑视图渲染。 4. **mybatis-config.xml** 则作为 MyBatis 的基础配置文件,补充了额外的功能选项。 这些文件相互协作,共同构建了一个完整的 SSM 架构应用。 --- #### 常见问题及解决方法 1. 如果服务无法找到对应的 Bean,则需确认是否正确注册了相关组件扫描范围或手动定义了 Bean 实例[^4]。 2. 当遇到数据库操作异常时,请检查 `sqlSessionFactory` 是否成功加载了正确的 Mapper 文件位置。 3. 若页面显示错误提示未找到视图名称,请验证视图解析器前缀后缀是否匹配实际目录结构。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值