前言

经历了长达快三个月的学习,终于把SSM(Spring + SpringMVC + Mybatis)给学习完了,然后看了下SSM整合的案例,还是比较繁琐的,在此记录一下SSM整合的全部过程!

本机环境

  • 以下只是我的机子的环境版本

编辑器:IDEA2020.1
Maven:v3.6.3版本
Tomcat:v9.0.38版本
MySQL:v5.7.26版本

Jar包列表

        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</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.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

复制粘贴~~~

会出现的问题:resources导出不正常的问题。解决方式如下:

  • pom.xml文件中添加以下代码
    <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>

会出现的问题:Jar包导入不进项目的问题。解决方式如下:

Jar包问题
WEB-INF文件夹中创建lib目录,再把你的所有Jar包添加进入即可。

步骤

  1. 先创建一个数据库,新建一个user表,方便搭建完后做个小案例,结构比较简单,就不配SQL了!
    数据库结构图
  2. 创建好目录结构!controllerpojoservicemapper,并且创建对应user表中的实体类。
    实体类结构图

Mybatis层编写

  1. 首先在resources目录下创建db.properties文件 换成自己的数据库信息即可。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_ceshi?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root 
  1. 编写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>

    <typeAliases>
        <!--给实体类添加别名-->
        <package name="com.awei.pojo"/>
    </typeAliases>
    <mappers>
        <mapper class="com.awei.mapper.UserMapper"/>
    </mappers>

</configuration>
  1. 编写Dao层的Mapper接口
public interface UserMapper {
    //获取用户列表
    List<User> getUserList();

    //添加一个用户
    int addUser(User user);

    //删除一个用户
    int deleteUser(@Param("id") int id);
}

只做了三个小功能演示。

  1. 编写对应的Mapper.xml文件!
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.awei.mapper.UserMapper">

    <select id="getUserList" resultType="User">
        select * from ssm_ceshi.user;
    </select>

    <insert id="addUser" parameterType="User">
        insert into ssm_ceshi.user(user,pass,age)
        values (#{user},#{pass},#{age});
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from ssm_ceshi.user
        where id = #{id};
    </delete>
</mapper>
  1. 编写对应的Service层接口和实现类

    • 接口
public interface UserService {
    //获取用户列表
    List<User> getUserList();

    //添加一个用户
    int addUser(User user);

    //删除一个用户
    int deleteUser(int id);
}
  • 实现类:
public class UserServiceImpl implements UserService{


    @Autowired
    private UserMapper userMapper;

    public List<User> getUserList() {
        return userMapper.getUserList();
    }

    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    public int deleteUser(int id) {
        return userMapper.deleteUser(id);
    }
}

OK,Mybatis层就配置完毕了

Spring层

  1. 新建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
       http://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"/>

    <!--第二部 配置c3p0连接池信息-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="5000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>


    <!--第三部 配置SQLSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入连接池-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置Mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>


    <!--第四步 配置扫描dao接口 实现动态注入到spring容器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入SQLSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

        <!--需要扫描的Mapper(dao)包-->
        <property name="basePackage" value="com.awei.mapper"/>
    </bean>
</beans>
  1. Spring 整合Service层 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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描service的bean-->
    <context:component-scan base-package="com.awei.service"/>


    <!--配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

Spring层也就搞定啦!!

SpringMVC整合

  1. 由于我们创建的是Maven项目 需要手动添加一下Web框架支持!
    添加框架支持
  2. 在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>springmvc</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>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!--处理全局乱码问题-->
    <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>
        <!--设置30分钟过期时间-->
        <session-timeout>30</session-timeout>
    </session-config>

</web-app>
  1. 在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
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!--开启注解支持-->
    <mvc:annotation-driven />
    <!--静态资源默认servlet配置-->
    <mvc:default-servlet-handler />

    <!--配置jsp视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--配置后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置要扫描的控制层的bean-->
    <context:component-scan base-package="com.awei.controller"/>

</beans>
  1. 创建模板解析器对应的目录 :WEB-INF/目录下创建jsp目录!
  2. 接着创建applicationContext.xml的总配置文件 把三个配置文件导入即可!

然后SSM基本就整合完了!! 接下来开始小案例演示!

项目的基本目录结构:
项目的基本结构

案例实现

  1. controller目录新建UserController
  2. 写入三个方法分别是显示用户列表添加用户数据删除用户数据
    具体代码如下:
@Controller
public class UserController {

    @Autowired
    private UserServiceImpl userService;


    @GetMapping("/showUser")
    public String showUser(Model model){
        List<User> userList = userService.getUserList();
        model.addAttribute("userList",userList);
        return "showUser";
    }


    @PostMapping("/addUser")
    public String addUser(User user,Model model){
        userService.addUser(user);
        return "redirect:/showUser";
    }

    @GetMapping("/deleteUser")
    public String deleteUser(int id){
        userService.deleteUser(id);
        return "redirect:/showUser";
    }
  • 对应的JSP代码如下:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示用户数据</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/addUser" method="post">
    <input type="text" name="user" placeholder="姓名">
    <input type="text" name="pass" placeholder="密码">
    <input type="text" name="age" placeholder="年龄">
    <input type="submit" value="添加">
</form>
<hr>
<table border="1">
    <tr>
        <td>ID</td>
        <td>姓名</td>
        <td>密码</td>
        <td>年龄</td>
        <td>操作</td>
    </tr>
    <c:forEach items="${userList}" var="user">
    <tr>
        <td>${user.id}</td>
        <td>${user.user}</td>
        <td>${user.pass}</td>
        <td>${user.age}</td>
        <td>
            <a href="${pageContext.request.contextPath}/deleteUser?id=${user.id}">删除</a>
        </td>
    </tr>
    </c:forEach>
</table>
</body>
</html>

到这里,这个小Demo就基本完成了,比较简单。以下为演示图

演示图

项目最后的目录结构图

最后结构图

最后修改:2020 年 11 月 02 日 11 : 06 PM
要饭啦!!!赞赏一点吧!!!