SpringMvc、Spring和Mybatis整合(SSM框架整合)

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&amp;useUnicode=true&amp;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&amp;useUnicode=true&amp;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教学视频,真的非常优秀。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章