SpringMvc、Spring和Mybatis整合
就是我們通常的SSM整合。
先創建一個web的Maven項目。
1.SpringMvc環境搭建
1.1 導入SpringMvc所需要的依賴
在項目的pom.xml文件中添加如下:
<!--Spring的大部分依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!--jackson依賴-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
1.2 編寫SpringMvc配置文件
在resources目錄下創建spring-mvc.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: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">
<!--自動掃描包,讓指定包下的註解生效,由Spring容器統一管理 這裏的掃描包需要和自己存放Controller類的包一致-->
<context:component-scan base-package="com.ara.controller"/>
<!--讓Spring不處理靜態資源-->
<mvc:default-servlet-handler />
<!--支持mvc註解驅動-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true" >
<!--配置消息轉換爲UTF-8編碼-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<!--使用MappingJackson2HttpMessageConverter處理轉換-->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--視圖解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!--視圖前綴-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--視圖後綴-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
博主這裏習慣將所有的控制器Controller存放在com.ara.controller
包下。
1.3 配置web.xml文件
在web/WEB-INF下出web.xml中添加如下:
<!-- 配置SpringMvc的DispatcherServlet來攔截所有請求 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置SpringMvc的加載文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 配置SpringMvc的DispatcherServlet的啓動級別和服務器一致 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置SpringMvc的DispatcherServlet來攔截所有請求 -->
<!-- /:表示不攔截.jsp -->
<!-- /*:表示攔截.jsp -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置SpringMvc的CharacterEncodingFilter來過濾編碼 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 設置編碼參數爲UTF-8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 配置SpringMvc的CharacterEncodingFilter來過濾所有請求 -->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
1.4 編寫測試Controller
在我們指定存放Controller的包下(博主這裏是com.ara.controller
)創建一個HelloController類,其內容如下:
package com.ara.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String hello(){
System.out.println("hello SpringMvc 你好");
return "hello SpringMvc 你好";
}
}
1.5 測試
開啓Tomcat,瀏覽器訪問如下:
當出現上面情況,說明我們的SpringMvc的環境就已經搭建成功了。
2. Spring整合SpringMvc
Spring和SpringMvc本就是一家,說實話,整合起來。。。可能說不上整合吧,哈哈。
我們還是編寫一個關於業務層的Spring配置文件spring-service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 開啓註解支持 -->
<context:annotation-config/>
<!-- 掃描包Service實現類 -->
<context:component-scan base-package="com.ara.service"/>
</beans>
這個配置文件就專門來存放管理service層的對象。
然後我們編寫一個總配置文件application.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 引入spring-service.xml配置文件 -->
<import resource="spring-service.xml"/>
<!-- 引入spring-mvc.xml配置文件 -->
<import resource="spring-mvc.xml"/>
</beans>
上述配置文件都存放在resources目錄下。
現在我們所需要處理的就是怎麼讓項目啓動時,加載application.xml文件,這也很簡單,更改web.xml的加載文件即可。
編寫service層,在com.ara.service下創建測試HelloService接口:
package com.ara.service;
public interface HelloService {
String hello();
}
在com.ara.service.impl編寫HelloService的實現類HelloServiceImpl:
package com.ara.service.impl;
import com.ara.service.HelloService;
import org.springframework.stereotype.Service;
@Service
public class HelloServiceImpl implements HelloService {
public String hello() {
System.out.println("hello Service 你好");
return "hello Service!";
}
}
然後修改HelloController如下:
package com.ara.controller;
import com.ara.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String hello(){
System.out.println("hello SpringMvc 你好");
return helloService.hello();
}
}
然後重啓Tomcat測試如下:
到此,Spring整合SpringMvc就算是成功了。
3.Mybatis環境搭建
準備工作
數據庫數據準備如下:
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user`(
`id` INT PRIMARY KEY AUTO_INCREMENT COMMENT '主鍵id',
`name` VARCHAR(30) NOT NULL COMMENT '用戶名',
`password` VARCHAR(30) NOT NULL COMMENT '密碼'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO USER(`name`,`password`) VALUES('Ara_Hu','123456'),('張三','123456'),('李思','123456'),('王武','123456'),('趙柳','123456'),('田七','123456');
創建對應實體類,實體類存放在com.ara.pojo包下:
package com.ara.pojo;
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
3.1 導入需要的依賴
在pom.xml中導入依賴如下:
<!-- Mysql驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- Mybatis依賴 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
這裏需要在pom.xml添加如下:
<build>
<resources>
<!--讓它掃描src/main/resources下的所有properties和xml文件-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<!--讓它掃描src/main/java下的所有properties和xml文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
防止後面編寫的XXXMapper.xml不能正常導出。
3.2 編寫Mybatis的配置文件
在resources目錄下創建Mybatis的配置文件mybatis-config.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>
<!-- mybatis開啓駝峯命名轉換 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- mybatis設置日誌打印爲控制檯輸出 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- mybatis別名設置 -->
<typeAliases>
<!-- 指定包com.ara.pojo -->
<package name="com.ara.pojo" />
</typeAliases>
<!-- 配置數據源 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 指定mapper.xml文件的包 -->
<mappers>
<package name="com.ara.mapper"/>
</mappers>
</configuration>
3.3 編寫dao層代碼
這裏將dao層的內容放置在com.ara.mapper包下。
先創建UserMapper接口:
package com.ara.mapper;
import com.ara.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUsers();
}
再編寫其對應的Mapper.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.ara.mapper.UserMapper">
<select id="getUsers" resultType="User">
select * from user;
</select>
</mapper>
編寫Mybatis的工具類MybatisUtils:
package com.ara.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
//SqlSessionFactory對象
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//加載Mybatis配置文件
InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
//通過SqlSessionFactoryBuilder構建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
//返回SqlSession的方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3.4 編寫測試代碼
在com.ara.test包下創建測試類:
package com.ara.test;
import com.ara.mapper.UserMapper;
import com.ara.pojo.User;
import com.ara.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MybatisTest {
@Test
public void test(){
//獲取sqlSession對象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//通過sqlSession獲取對應Mapper對象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
//遍歷循環輸出
for (User user : users) {
System.out.println(user);
}
//關閉sqlSession對象
sqlSession.close();
}
}
運行結果如下:
此時,Mybatis環境搭建成功。
4. Spring整合Mybatis
對於Spring,我們知道它的核心之一就是IOC容器,我們使用Spring整合Mybatis,就是想辦法將Mybatis的對象注入到Spring的IOC容器中即可。
4.1 導入整合依賴
在pom.xml中添加如下:
<!-- Mybatis整合Spring的依賴 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!-- Spring的JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
4.2 編寫dao層的配置文件
在resources目錄下編寫數據庫連接的配置文件db.properties,其內容如下:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
在resources目錄下創建spring-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 關聯數據庫文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!--
DataSource:使用Spring的數據源替換Mybatis的配置
我們這裏使用Spring提供的JDBC:org.springframework.jdbc.datasource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 這裏的參數值通過表達式從db.properties取出 -->
<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>
<!-- 配置SqlSessionFactory對象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入數據庫連接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 配置掃描Dao接口包,動態實現Dao接口注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao接口包 -->
<property name="basePackage" value="com.ara.mapper"/>
</bean>
</beans>
這裏,我們使用Spring管理了數據源、SqlSessionFactory對象和掃描包,之前Mybatis的配置文件就“壓縮”如下:
<?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>
<!-- mybatis開啓駝峯命名轉換 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- mybatis設置日誌打印爲控制檯輸出 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- mybatis別名設置 -->
<typeAliases>
<!-- 指定包com.ara.pojo -->
<package name="com.ara.pojo" />
</typeAliases>
<!-- 配置數據源 -->
<!-- <environments default="development">-->
<!-- <environment id="development">-->
<!-- <transactionManager type="JDBC"/>-->
<!-- <dataSource type="POOLED">-->
<!-- <property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!-- <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8"/>-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="password" value="rootroot"/>-->
<!-- </dataSource>-->
<!-- </environment>-->
<!-- </environments>-->
<!-- 指定mapper.xml文件的包 -->
<!-- <mappers>-->
<!-- <package name="com.ara.mapper"/>-->
<!-- </mappers>-->
</configuration>
我們的測試類和Mybatis的工具類都可以直接捨棄了。
4.3 將dao層的配置添加到總配置文件中
在application.xml中引入spring-dao.xml文件,如下:
4.4 編寫測試代碼
在service層中編寫UserService接口:
package com.ara.service;
import com.ara.pojo.User;
import java.util.List;
public interface UserService {
List<User> getUsers();
}
編寫其實現類UserServiceImpl:
package com.ara.service.impl;
import com.ara.mapper.UserMapper;
import com.ara.pojo.User;
import com.ara.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUsers() {
return userMapper.getUsers();
}
}
在controller層中編寫UserController:
package com.ara.controller;
import com.ara.pojo.User;
import com.ara.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUsers")
@ResponseBody
public List<User> getUsers(){
return userService.getUsers();
}
}
4.5 測試
重啓Tomcat,瀏覽器訪問結果如下:
到此,三個框架整合就成功了。
關於Java的學習,博主這裏推薦一個優秀的Java講師 狂神說,嗶哩嗶哩搜索狂神說,就可以查看狂神老師的所有Java教學視頻,真的非常優秀。