1、基本概念
1.1、Spring
Spring是一個開源框架,Spring是於2003 年興起的一個輕量級的Java 開發框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中闡述的部分理念和原型衍生而來。它是為了解決企業應用開發的複雜性而建立的。Spring使用基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅限於伺服器端的開發。從簡單性、可測試性和鬆耦合的角度而言,任何Java應用都可以從Spring中受益。 簡單來說,Spring是一個輕量級的控制反轉(IoC)和麵向切面(AOP)的容器框架。
1.2、SpringMVC
Spring MVC屬於SpringFrameWork的後續產品,已經融合在Spring Web Flow裡面。Spring MVC 分離了控制器、模型物件、分派器以及處理程式物件的角色,這種分離讓它們更容易進行定製。
1.3、Mybatis
MyBatis 本是apache的一個開源專案iBatis, 2010年這個專案由apache software foundation 遷移到了google code,並且改名為MyBatis 。MyBatis是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎所有的JDBC程式碼和引數的手工設定以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始對映,將介面和 Java 的POJOs(Plain Old Java Objects,普通的 Java物件)對映成資料庫中的記錄。
2、操作流程
1、建立Maven工程
2、匯入座標建立依賴
<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>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--資料庫驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- 資料庫連線池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<build>
<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>
3、編寫實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
public class User implements Serializable {
private Integer id;
private String username;
private String sex;
private String address;
}
4、編寫持久層
public interface UserDao {
/**
* 查詢所有使用者資訊
* */
List<User> findAll();
/**
* 增加使用者
* */
void create(User user);
}
5、編寫業務層介面
public interface UserService {
/**
* 查詢所有使用者資訊
* */
List<User> findAll();
/**
* 增加使用者
* */
void create(User user);
}
6、編寫業務層介面實現
public class UserServiceImpl implements UserService {
@Override
public List<User> findAll() {
System.out.println("查詢所有使用者");
return null;
}
@Override
public void create(User user) {
System.out.println("增加一個使用者資訊");
}
}
##7、編寫控制層
```java
public class UserController {
}
SSM整合
1、Spring相關配置
Spring.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:context="http://www.springframework.org/schema/context"
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/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">
</beans>
Spring的相關配置
<?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: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/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">
<!--開啟註解掃描-->
<context:component-scan base-package="com.xiaohe">
<!--<context:include-filter type="" expression=""/>-->
<!--排除Controller註解,不需要掃描的這類-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
業務了邏輯層實現類程式碼
@Service(value = "userService")
public class UserServiceImpl implements UserService {
@Override
public List<User> findAll() {
System.out.println("查詢所有使用者");
return null;
}
##1、SpringMVC配置
@Override
public void create(User user) {
System.out.println("增加一個使用者資訊");
}
}
測試Spring配置是否成功,新建一個測試Demo
@Test
public void testSpring(){
//獲取spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserServiceImpl userService = context.getBean("userService", UserServiceImpl.class);
userService.findAll();
}
}
控制檯輸出
成功
2、SpringMVC相關配置
Web.xml配置
<?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">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我們這裡載入的是總的配置檔案,之前被這裡坑了!-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter-->
<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>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session過期時間-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
配置SpringMVC配置檔案相關約束
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
Springmvc相關配置
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--掃描Controller相關注解-->
<context:component-scan base-package="com.xiaohe">
<!--表示只掃描Controller註解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置檢視解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置字首-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!--配置字尾-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--設定靜態程式碼不過濾-->
<mvc:default-servlet-handler/>
<!--開啟Spring註解支援-->
<mvc:annotation-driven />
</beans>
controller配置
@Controller
@RequestMapping("/user")
public class UserController {
//查詢所有的使用者資訊
@RequestMapping("/findAll")
public String findAll(){
System.out.println("查詢到所有的使用者列表");
return "userList";
}
}
index.jsp
<html>
<body>
<a href="/user/findAll">UserList</a>
</body>
</html>
userList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>使用者列表頁面</title>
</head>
<body>
<h1>UserList</h1>
</body>
</html>
測試
成功
3、Spring-SpringMVC整合
在Web.xml裡面新增監聽器
<!--配置Spring監聽器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
4、Spring-mybbatis整合
配置Mybatis-config
mybatis--config的頭部資訊
<?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">
mybatis-config配置
<?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>
<!--配置資料庫環境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--配置對映檔案-->
<!--使用註解-->
<mappers>
<package name="com.xiaohe.dao"/>
</mappers>
</configuration>
編寫測試類
@Test
public void testMybatis() throws IOException {
//載入配置檔案
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> user = userDao.findAll();
for (User user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}
}
結果
成功
Spring整合Mybatis
在spring.xml新增
<!--配置session工廠-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--掃描dao介面-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xiaohe.dao"/>
</bean>
測試成功
至此為止SSM整合完成
補充事務
在Spring.xml新增
<!--配置事務管理器-->
<!--配置事務通知-->
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<!--select方法-->
<tx:method name="find" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP相關增強-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.xiaohe.service.impl.*ServiceImpl(..))"></aop:advisor>
</aop:config>