0%

SSM基本配置

SSM 框架基本配置详解:从 Web 到事务的完整搭建

SSM(Spring + SpringMVC + MyBatis)是 Java 企业级开发的经典框架组合,通过 Spring 的 IOC 容器管理对象,SpringMVC 处理 Web 请求,MyBatis 简化数据库操作,三者协同实现高效开发。本文基于提供的配置文件,详细解析 SSM 框架的核心配置与工作流程。

Web.xml 配置:Web 应用的入口

web.xml是 Web 应用的部署描述符,负责配置 Servlet、过滤器、监听器等 Web 组件,是 SSM 框架与 Web 容器(如 Tomcat)交互的入口。

核心配置解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?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">

<!-- 1. 错误页面配置 -->
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error500.jsp</location>
</error-page>

<!-- 2. 加载Spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 指定Spring配置文件路径(支持通配符) -->
<param-value>WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<!-- Spring的上下文加载监听器,启动时初始化Spring容器 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 3. 配置SpringMVC前端控制器 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- SpringMVC配置文件路径 -->
<param-value>WEB-INF/classes/spring/springmvc.xml</param-value>
</init-param>
<!-- 可选:设置启动顺序(1表示Web容器启动时立即加载) -->
<!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<!-- 拦截所有请求(除JSP外),由DispatcherServlet处理 -->
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 4. 解决POST请求乱码的过滤器 -->
<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>

<!-- 5. 欢迎页配置 -->
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>

关键作用:

  • Spring 容器初始化:通过ContextLoaderListener加载applicationContext-*.xml,创建 Spring 的 IOC 容器;
  • SpringMVC 入口DispatcherServlet作为前端控制器,接收所有请求并分发到对应的 Controller;
  • 编码处理CharacterEncodingFilter统一设置请求编码为 UTF-8,解决中文乱码问题;
  • 错误处理:指定 404 和 500 错误的跳转页面,提升用户体验。

SpringMVC 配置(springmvc.xml):Web 层核心配置

springmvc.xml配置 SpringMVC 的核心组件,包括视图解析器、Controller 扫描、拦截器等,负责请求处理与响应。

核心配置解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1. 视图解析器:将Controller返回的逻辑视图名转换为物理视图路径 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property> <!-- 视图前缀(JSP文件所在目录) -->
<property name="suffix" value=".jsp"></property> <!-- 视图后缀 -->
</bean>

<!-- 2. 组件扫描:自动扫描并注册Controller -->
<context:component-scan base-package="com.zhanghe.study">
<!-- 可选:仅扫描@Controller注解的类 -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->
</context:component-scan>

<!-- 3. 启用注解驱动:自动注册处理器映射器和适配器 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

<!-- 4. 自定义参数类型转换器(如日期格式转换) -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.zhanghe.study.controller.converter.DateConverter"/>
</list>
</property>
</bean>

<!-- 5. 静态资源访问配置:允许直接访问CSS、JS、图片等资源 -->
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/imgdata/**" location="/imgdata/" />

<!-- 6. 配置拦截器:对请求进行预处理或后处理(如登录验证) -->
<mvc:interceptors>
<bean class="com.zhanghe.study.interceptor.CustomInterceptor"></bean>
</mvc:interceptors>

<!-- 7. 文件上传解析器:处理multipart/form-data类型的请求 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="9242880"></property> <!-- 最大上传大小(9MB) -->
</bean>

<!-- 8. 全局异常处理器:统一处理Controller层抛出的异常 -->
<bean id="exceptionResolver" class="com.zhanghe.study.exception.OverallExceptionResolver"></bean>
</beans>

关键作用:

  • 视图解析InternalResourceViewResolver"index"转换为/index.jsp,简化视图路径配置;
  • 注解驱动mvc:annotation-driven自动注册RequestMappingHandlerMapping(处理器映射器)和RequestMappingHandlerAdapter(处理器适配器),支持@RequestMapping等注解;
  • 静态资源mvc:resources避免静态资源被DispatcherServlet拦截,确保 CSS、JS 等文件正常加载;
  • 拦截器:可在请求到达 Controller 前(如登录验证)或响应返回后(如日志记录)执行自定义逻辑;
  • 异常处理:全局异常处理器统一捕获异常,避免错误信息直接暴露给用户。

Spring 配置(applicationContext-*.xml):Service 与数据层配置

Spring 配置文件通常按功能拆分(如applicationContext-dao.xmlapplicationContext-service.xml),这里主要配置数据源、MyBatis 集成和 Service 扫描。

核心配置解析(以 DAO 层为例)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- 1. 加载数据库配置文件 -->
<context:property-placeholder location="/WEB-INF/classes/jdbc.properties"/>

<!-- 2. 配置数据源(使用dbcp2连接池) -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/> <!-- 数据库驱动 -->
<property name="url" value="${jdbc.url}"/> <!-- 数据库连接地址 -->
<property name="username" value="${jdbc.username}"/> <!-- 用户名 -->
<property name="password" value="${jdbc.password}"/> <!-- 密码 -->
<!-- 可选配置:连接池大小、超时时间等 -->
<!-- <property name="initialSize" value="5"/> -->
</bean>

<!-- 3. 配置MyBatis的SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/> <!-- 关联数据源 -->
<property name="configLocation" value="/WEB-INF/classes/mybatis/SqlMapConfig.xml"/> <!-- MyBatis全局配置文件 -->
<!-- 可选:配置别名包、映射文件路径等 -->
<!-- <property name="typeAliasesPackage" value="com.zhanghe.study.pojo"/> -->
</bean>

<!-- 4. 配置MyBatis的Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zhanghe.study.mapper"/> <!-- 扫描Mapper接口所在包 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 关联SqlSessionFactory -->
</bean>
</beans>

关键作用:

  • 数据源配置:使用BasicDataSource管理数据库连接,避免频繁创建和关闭连接,提升性能;
  • MyBatis 集成SqlSessionFactoryBean将 MyBatis 的SqlSessionFactory交给 Spring 管理,简化 MyBatis 配置;
  • Mapper 扫描MapperScannerConfigurer自动扫描 Mapper 接口并创建实现类,无需手动配置MapperFactoryBean

事务配置:保证数据一致性

事务配置通过 Spring 的声明式事务管理,确保 Service 层的数据库操作符合 ACID 特性。

核心配置解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- 1. 配置事务管理器(基于数据源) -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/> <!-- 关联数据源 -->
</bean>

<!-- 2. 配置事务通知(定义事务规则) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 对save*/insert*/update*/delete*开头的方法应用事务 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<!-- 对查询方法设置为只读,提升性能 -->
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 3. AOP配置:将事务通知织入Service层 -->
<aop:config>
<!-- 切入点:匹配Service实现类的所有方法 -->
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.zhanghe.study.service.impl.*.*(..))"/>
</aop:config>
</beans>

关键作用:

  • 事务管理器DataSourceTransactionManager基于数据源管理事务,支持 JDBC(包括 MyBatis)的事务控制;
  • 事务规则:通过tx:method定义不同方法的事务传播行为(如REQUIRED表示如果当前没有事务,则创建新事务);
  • AOP 织入:通过切入点表达式将事务规则应用到service.impl包下的所有方法,实现声明式事务(无需手动编写try-catch)。

SSM 配置整体流程总结

  1. Web 容器启动:加载web.xml,通过ContextLoaderListener初始化 Spring 容器(加载applicationContext-*.xml),并启动DispatcherServlet初始化 SpringMVC 容器(加载springmvc.xml)。
  2. 请求处理:
    • 客户端请求被DispatcherServlet接收,通过处理器映射器找到对应的 Controller;
    • Controller 调用 Service 层方法,Service 层通过 Spring 注入的 Mapper 接口操作数据库;
    • 事务管理器自动管理 Service 层的事务,确保数据一致性。
  3. 响应返回:Controller 返回逻辑视图名,视图解析器转换为物理 JSP 路径,渲染页面并返回给客户端。

最佳实践与注意事项

  1. 配置拆分:将 Spring 配置按功能拆分(DAO、Service、事务),提高可维护性;
  2. 包扫描范围context:component-scan需精准定位(如 Controller 只扫描controller包,避免重复扫描);
  3. 静态资源处理mvc:resourcesmappinglocation需正确匹配,避免 404 错误;
  4. 事务切入点:确保aop:pointcut准确匹配 Service 实现类,避免事务不生效;
  5. 连接池配置:生产环境需合理设置连接池参数(如最大连接数、超时时间),避免性能瓶颈

欢迎关注我的其它发布渠道

表情 | 预览
快来做第一个评论的人吧~
Powered By Valine
v1.3.10