SSM(springmvc + spring + MyBatis)整合開發
1、SSM編程的基本介紹
SSM 編程,即 springmvc + spring + MyBatis 整合,是當前最為流行的 javaEE 開發技術架構。
- springmvc:視圖層、界面層,負責接收請求,返回處理結果
- spring:業務層,管理 service、dao、工具類對象
- MyBatis:持久層,負責操作數據庫
SSM框架是spring MVC ,Spring和Mybatis框架的整合,是標準的MVC模式,將整個系統劃分為表現層(web),controller層,service層,dao層四層,使用spring MVC負責請求的轉發和視圖管理。Spring實現業務對象管理,Mybatis作為數據對象的持久化引擎。

- 表現層(web):通俗講就是展現給用戶的界面,即用戶在使用一個系統的時候他的所見所得。
- 業務邏輯層(service):針對具體問題的操作,也可以說是對數據層的操作,對數據業務邏輯處理。
- 數據訪問層(dao):該層所做事務直接操作數據庫,針對數據的增添、刪除、修改、更新、查找等。
2、SSM整合示例
首先,先在 idea 中通過 maven 創建一個 web 項目,手動添加 src/main/java 和 src/main/resources 目錄。初始目錄結構如下:

2.1、建表語句
下面會用到student表,建表語句如下:
DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(80) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.2、pom.xml 文件配置
在 pom.xml 配置文件中添加依賴,并且配置一些 build 選項:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>mybatis_spring</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>mybatis_spring Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--jsp--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <!--springmvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--事務相關--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> </dependencies> <build> <!--將src下以及resources目錄下的properties、xml文件編譯后寫出到target目錄--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
2.3、web.xml 文件配置
在 web.xml 文件中配置 springmvc 和 spring:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- SpringMVC的前端控制器 --> <servlet> <servlet-name>springmvcTest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 自定義springmvc的配置文件的位置--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/dispatcherServlet.xml</param-value> <!--指定配置文件的位置--> </init-param> <!-- 指定該servlet對象在tomcat啟動時即創建--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvcTest</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--注冊spring監聽器--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--注冊字符集過濾器 強制utf-8編碼--> <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> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2.4、新建包、目錄、配置文件
在 src/main/resouces 目錄下新建文件夾 conf,用來存放一系列的配置文件。如在上面 web.xml 配置中所指定的 springmvc 的配置文件 dispatcherServlet.xml、spring 的配置文件 applicationContext.xml、jdbc.properties 和 mybatis.xml 。
在 src/main/java 目錄下新建包如 mypackage,在該包新建一系列包,如 service、dao、domain、controller。
最后目錄結構如下:

2.5、spring 的配置文件 applicationContext.xml
主要是配置service和dao
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- spring的配置文件:聲明service、dao、工具類等對象--> <!--獲取數據庫連接信息--> <context:property-placeholder location="classpath:conf/jdbc.properties" /> <!--使用druid數據源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!--創建SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:conf/mybatis.xml" /> </bean> <!--聲明mybatis掃描器,創建dao對象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <property name="basePackage" value="mypackage.dao" /> </bean> <!--聲明 service的注解@Service所在包的位置--> <context:component-scan base-package="mypackage.service" /> <!--事務配置(注解或aspectj)--> </beans>
2.6、springmvc 的配置文件 dispatcherServlet.xml
配置spirngMVC,主要是組件controller、視圖view的配置
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- springmvc的配置文件,聲明controller和其它web相關的對象--> <!--組件掃描器--> <context:component-scan base-package="mypackage.domain,mypackage.dao,mypackage.service,mypackage.controller" /> <!--視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!--注解驅動--> <mvc:annotation-driven /> </beans>
2.7、數據庫配置文件 jdbc.properties
數據庫配置文件配置數據庫連接的基本信息,示例:
jdbc.url=jdbc:mysql://localhost:3306/userDB jdbc.username=root jdbc.password=123456
上面的 userDB 為數據庫名稱。
2.8、mybatis 的配置文件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> <!--開啟mybatis日志--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--配置別名--> <typeAliases> <!-- 實體類所在的包名--> <package name="mypackage.domain"/> </typeAliases> <!--sql mapper文件的位置--> <mappers> <package name="mypackage.dao"/> </mappers> </configuration>
2.9、編寫java代碼
最終的 java 代碼目錄結構如下:

2.9.1、先建立實體類(domain、model層)
實體層用于存放我們的實體類,與數據庫中的屬性值基本保持一致,實現set和get的方法。
Student 類:
package mypackage.domain; public class Student { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
2.9.2、controller 層
負責具體模塊的業務流程控制(獲取參數(前端傳過來)返回響應(前端或數據庫或一個指定路徑)),需要調用service邏輯設計層的接口來控制業務流程(導入service層)。
StudentController 類:
package mypackage.controller; import mypackage.domain.Student; import mypackage.service.StudentService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import java.util.List; @Controller @RequestMapping("/student") public class StudentController { @Resource private StudentService service; //添加學生 @RequestMapping("/addStudent.do") public ModelAndView addStudent(Student student){ ModelAndView mv =new ModelAndView(); String tips = "注冊失敗"; //調用service處理 int nums = service.addStudent(student); if(nums > 0){ tips = "學生【"+student.getName()+"】注冊成功"; } //添加數據 mv.addObject("tips", tips); //指定結果頁面(邏輯名稱) mv.setViewName("result"); return mv; } //查詢 返回json @RequestMapping("/queryStudent.do") @ResponseBody public List<Student> queryStudent(Student student){ //省略參數檢查以及數據處理 List<Student> students = service.findStudents(); return students; } }
2.9.3、service 層
service層(接口類)為controller層的類提供接口進行調用,一般就是自己寫的方法封裝起來,具體實現在serviceImpl中。servicedmpl(實現service層,整合service和dao)(導入dao層)(接口實現類)
StudentService 接口:
package mypackage.service; import mypackage.domain.Student; import java.util.List; public interface StudentService { int addStudent(Student student); List<Student> findStudents(); }
實現類 StudentServiceImpl :
package mypackage.service.impl; import mypackage.dao.StudentDao; import mypackage.domain.Student; import mypackage.service.StudentService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class StudentServiceImpl implements StudentService { @Resource private StudentDao studentDao; @Override public int addStudent(Student student) { int nums = studentDao.insertStudent(student); return nums; } @Override public List<Student> findStudents() { return studentDao.selectStudents(); } }
2.9.4、dao 層(可以理解為mapper層)
dao層(接口類)對數據庫進行數據持久化操作,他的方法語句是直接針對數據庫操作的,主要實現一些增刪改查操作,在Mybatis中方法主要與與xxxMapper.xml內相互一一映射。
StudentDao 接口:
package mypackage.dao; import mypackage.domain.Student; import java.util.List; public interface StudentDao { int insertStudent(Student student); List<Student> selectStudents(); }
mybatis 對應的SQL 文件,文件名跟上面的 dao 類一樣,即名為:StudentDao.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="mypackage.dao.StudentDao"> <select id="selectStudents" resultType="Student"> select id,name,age from student order by id desc </select> <insert id="insertStudent"> insert into student(name,age) values(#{name},#{age}) </insert> </mapper>
2.10、編寫 jsp 驗證
jsp 文件最終目錄結構如下:

index.jsp :
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme()+"://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>Title</title> <base href="<%=basePath%>"> </head> <body> <table align="center"> <tr> <td><a href="addStudent.jsp">注冊學生</a></td> </tr> <tr> <td><a href="listStudent.jsp">瀏覽學生</a></td> </tr> </table> </body> </html>
listStudent.jsp :
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme()+"://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>查詢學生 使用ajax</title> <base href="<%=basePath%>"> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $.ajax({ url:"student/queryStudent.do", dataType:"json", success:function(data){ $.each(data, function(i,n){ $("#info").append("<tr>") .append("<td>"+n.id+"</td>") .append("<td>"+n.name+"</td>") .append("<td>"+n.age+"</td>") .append("</tr>") }) } }) }) </script> </head> <body> <table align="center"> <thead> <tr> <td>學號</td> <td>姓名</td> <td>年齡</td> </tr> </thead> <tbody id="info"> </tbody> </table> </body> </html>
addStudent.jsp :
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme()+"://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>Title</title> <base href="<%=basePath%>"> </head> <body> <div align="center"> <form action="student/addStudent.do" method="post"> <table> <tr> <td>姓名</td> <td><input type="text" name="name"></td> </tr> <tr> <td>年齡</td> <td><input type="text" name="age"></td> </tr> <tr> <td> </td> <td><input type="submit" value="提交"></td> </tr> </table> </form> </div> </body> </html>
jsp/result.jsp :
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 結果:${tips} </body> </html>

浙公網安備 33010602011771號