本文將詳細講解如何整合Spring、Spring MVC和MyBatis(SSM框架),通過一個人員信息查詢案例展示完整開發流程。所有代碼基于提供的文件實現。
一、項目結構
src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── qcby/
│ │ ├── controller/ # 控制層
│ │ │ └── PersonController.java
│ │ ├── dao/ # 數據訪問層
│ │ │ └── PersonDao.java
│ │ ├── entity/ # 實體類
│ │ │ └── Person.java
│ │ └── service/ # 服務層
│ │ ├── PersonService.java
│ │ └── impl/
│ │ └── PersonServiceImpl.java
│ ├── resources/
│ │ ├── mapper/ # MyBatis映射文件
│ │ │ └── PersonMapper.xml
│ │ ├── jdbc.properties # 數據庫配置
│ │ ├── spring.xml # Spring配置
│ │ └── SpringMVC.xml # Spring MVC配置
│ └── webapp/
│ ├── html/
│ │ ├── index.html # 首頁
│ │ └── person.html # 人員頁面
│ └── WEB-INF/
│ └── web.xml # Web配置
二、核心實現步驟
1. 實體類(Person.java)
package com.qcby.entity;public class Person {private Integer id;private String name;private String sex;private Integer age;private String idCard;private String phone;// Getter/Setter和toString()省略
}
2. MyBatis映射文件(PersonMapper.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.dao.PersonDao"><select id="findAll" resultType="Person">SELECT id, name, sex, age, idCard, phone FROM person</select>
</mapper>
3. 控制層(PersonController.java)
@Controller
public class PersonController {@Autowiredprivate PersonService personService;// 跳轉到人員頁面@RequestMapping("/toPerson")public String toPerson() {return "person"; // 對應html/person.html}// 查詢所有人員(返回JSON)@RequestMapping("/findAll")@ResponseBodypublic List<Person> findAll() {return personService.findAll();}
}
4. 服務層(PersonServiceImpl.java)
@Service
public class PersonServiceImpl implements PersonService {@Autowiredprivate PersonDao personDao;@Overridepublic List<Person> findAll() {return personDao.findAll();}
}
三、關鍵配置詳解
1. Spring配置(spring.xml)
<!-- 數據源配置 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="url" value="${jdbc.url}"/><property name="driverClassName" value="${jdbc.driver}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/>
</bean><!-- MyBatis整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="typeAliasesPackage" value="com.qcby.entity"/><property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean><!-- Mapper接口掃描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.qcby.dao"/>
</bean>
2. Spring MVC配置(SpringMVC.xml)
<!-- 視圖解析器(Thymeleaf) -->
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"><property name="templateEngine" ref="templateEngine"/><property name="characterEncoding" value="UTF-8"/>
</bean><bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"><property name="templateResolver" ref="templateResolver"/>
</bean><bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver"><property name="prefix" value="/html/"/><property name="suffix" value=".html"/>
</bean><!-- 支持JSON響應 -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
3. Web配置(web.xml)
<!-- 字符編碼過濾器 -->
<filter><filter-name>encodingFilter</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><!-- Spring MVC前端控制器 -->
<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:SpringMVC.xml</param-value></init-param>
</servlet>
四、前端頁面示例
1. 首頁(index.html)
<!DOCTYPE html>
<html>
<head><title>首頁</title>
</head>
<body><h1>歡迎使用人員管理系統</h1><a href="/toPerson">查看人員列表</a>
</body>
</html>
2. 人員頁面(person.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>人員信息</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body><div id="app"><table border="1"><tr><th>ID</th><th>姓名</th><th>性別</th><th>年齡</th></tr><tr v-for="person in personList"><td>{{ person.id }}</td><td>{{ person.name }}</td><td>{{ person.sex }}</td><td>{{ person.age }}</td></tr></table></div><script>new Vue({el: '#app',data: { personList: [] },mounted() {axios.get('/findAll').then(response => {this.personList = response.data;});}});</script>
</body>
</html>
五、技術亮點解析
依賴注入
通過@Autowired
實現層間解耦,Controller → Service → Dao 清晰調用鏈。聲明式事務
@Transactional
注解管理事務(需在Service層添加)。RESTful支持
@ResponseBody
自動將Java對象轉為JSON響應。連接池優化
使用Druid連接池提升數據庫訪問性能。前后端分離
前端通過Axios調用后端API,Vue.js動態渲染數據。
六、常見問題解決
問題1:靜態資源404
方案:在SpringMVC.xml中添加:
<mvc:resources mapping="/html/**" location="/html/"/>
問題2:事務不生效
方案:確保在spring.xml中開啟注解驅動:
<tx:annotation-driven transaction-manager="txManager"/>
問題3:中文亂碼
方案:檢查三處UTF-8配置:
web.xml的CharacterEncodingFilter
數據庫連接字符串的
characterEncoding=utf-8
視圖解析器的
characterEncoding
屬性
通過以上完整實現,我們構建了一個基于SSM框架的企業級應用。這種分層架構兼顧了靈活性和可維護性,適合快速開發復雜業務系統。