Spring+SpringMVC+Mybatis整合开发(超级详细)

2年前 (2022) 程序员胖胖胖虎阿
379 0 0

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 一、搭建基础工程
  • 二、Mybatis层编写以及数据库连接
  • 三、Spring整合Dao层
  • 四、Spring整合Service层
  • 五、Spring整合MVC层
  • 六、Spring整合dao-service-mvc三层
  • 七,Controller和视图层编写
  • 八,最终的项目结构如下
  • 九,启动tomcat测试

一、搭建基础工程

  1. 创建一个空的maven工程
  2. 添加pom依赖
<?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>ssm_mytest</groupId>
    <artifactId>ssm_mytest</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</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.27</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.16.12</version>
        </dependency>
    </dependencies>

    <!--    Maven静态资源导出-->
    <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>
  1. 添加WEB框架支持
  2. 补全项目结构
    4.1补全项目包结构
    4.2添加Spring的配置文件applicationContext.xml(用于最后整合所以的配置信息,暂且空置)
    最终的项目结构如下:
    Spring+SpringMVC+Mybatis整合开发(超级详细)

二、Mybatis层编写以及数据库连接

  1. 开始编写pojo类
package com.leshangju.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    int userId;
    String userName;
    int age;
    String sex;
}

  1. 编写Dao层Mapper接口
package com.leshangju.dao;

import com.leshangju.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
    List<User> getAllUser();

    User getUserById(@Param("userId") int userId);

    int addUser(User users);

    int deleteUser(@Param("userId") int userId);

    int updateUser(User user);
}

  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.leshangju.dao.UserMapper">

    <insert id="addUser" parameterType="User">
        insert into users(userName, age, sex)
        values (#{userName}, #{age}, #{sex})
    </insert>
    <delete id="deleteUser" parameterType="int">
        delete
        from users
        where userId = #{userId};
    </delete>
    <update id="updateUser" parameterType="User">
        update users
        set userName=#{userName},
            age=#{age},
            sex=#{sex}
        where userId = #{userId}
    </update>
    <select id="getUserById" parameterType="int" resultType="User">
        select *
        from users
        where userId = #{userId};
    </select>
    <select id="getAllUser" resultType="User">
        select *
        from users;
    </select>
</mapper>
  1. 编写service接口
package com.leshangju.service;

import com.leshangju.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserService {

    List<User> getAllUser();

    User getUserById(@Param("userId") int userId);

    int addUser(User users);

    int deleteUser(@Param("userId") int userId);

    int updateUser(User user);
}
  1. 编写impl实现类
package com.leshangju.service;

import com.leshangju.dao.UserMapper;
import com.leshangju.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserServiceImpl implements UserService {

    UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    @Override
    public User getUserById(int userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public int addUser(User users) {
        return userMapper.addUser(users);
    }

    @Override
    public int deleteUser(int userId) {
        return userMapper.deleteUser(userId);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }
}

  1. 创建mybatis的核心配置文件mybatis-config.xml,并将mapper绑定到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配置文件-->
    <!-- 打印SQL-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 原本是要去配置数据源信息的,但是和spring整合后,此步骤将交给spring去做-->
    <typeAliases>
        <!--作用是将实体包下的类起一个别名这样在mapper.xml中使用parameterType和resulttype的时候就能使用简写名,默认首字母小写-->
        <package name="com.leshangju.pojo"/>
    </typeAliases>
    <!-- 绑定mapper.xml文件-->
    <mappers>
        <mapper class="com.leshangju.dao.UserMapper"></mapper>
    </mappers>
</configuration>

三、Spring整合Dao层

  1. 创建数据库配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
  1. 创建spring整个Dao层的配置文件spring-dao.xml,主要整合数据库连接文件,连接池信息,sqlsessionFactory(需绑定Mybatis配置文件去读取配置Mapper信息),dao层动态注入到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"
       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">

    <!--1,关联数据库连接文件-->
    <context:property-placeholder location="classpath:database.properties"/>
    <!--2,连接池 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="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>
    <!-- 3,配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 绑定mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!-- 4,配置dao层,动态实现了接口可以注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.leshangju.dao"/>
    </bean>
</beans>

四、Spring整合Service层

  1. 创建spring整合service层的文件spring-service.xml,主要配置让spring去扫描service包的位置,配置impl中要注入的mapper信息,声明事务的提交方式,以及AOP事务的支持。
<?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下的包 -->
    <context:component-scan base-package="com.leshangju.service"/>
    <!-- 2业务类注入到spring-->
    <bean id="UserServiceImpl" class="com.leshangju.service.UserServiceImpl">
        <property name="userMapper" ref="userMapper"/>
    </bean>
    <!-- 3声明事务提交方式-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 4AOP事务支持-->
</beans>

五、Spring整合MVC层

1. 创建spring整合mvc层的文件spring-mvc.xml,主要配置springMVC静态资源过滤,开启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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
    <!--1.注解驱动-->
    <mvc:annotation-driven/>
    <!--2处理器映射器和处理器适配器-->
    <mvc:default-servlet-handler/>
    <!--3扫描包-->
    <context:component-scan base-package="com.leshangju.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

六、Spring整合dao-service-mvc三层

  1. 将以上配置的spring-dao.xml,spring-service.xml,spring-mvc.xml整合到applicationContext.xml中,同一个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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-dao.xml"/>
    <import resource="spring-sevice.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

确保如上的几个spring的xml文件都在一个Application Context中,否则整合会失败
Spring+SpringMVC+Mybatis整合开发(超级详细)

七,Controller和视图层编写

  1. 写controller
package com.leshangju.controller;

import com.leshangju.pojo.User;
import com.leshangju.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("UserServiceImpl")
    UserService service;

    @RequestMapping("/getAllUser")
    public String getAllUser(Model model) {
        List<User> allUser = service.getAllUser();
        model.addAttribute("list", allUser);
        return "allUser";
    }

    @RequestMapping(value = "/toAddUser")
    public String toAddUser() {
        return "addUser";
    }

    @RequestMapping(value = "/addUser")
    public String addUser(User user) {
        int i = service.addUser(user);
        return "redirect:/user/getAllUser";
    }

    @RequestMapping("/getUserById")
    public String updateUser(@RequestParam("userId") Integer id, Model model) {
        User userById = service.getUserById(id);
        model.addAttribute("user",userById);
        return "updateUser";
    }

    @RequestMapping("/updateUser")
    public String updateUser(User user) {
        int i = service.updateUser(user);
        return "redirect:/user/getAllUser";
    }

    @RequestMapping("/deleteUser/{userId}")
    public String deleteUser(@PathVariable("userId") int id) {
        int i = service.deleteUser(id);
        return "redirect:/user/getAllUser";
    }
}
  1. 在index.jsp中写跳转
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/user/getAllUser">进入用户概览页面</a>
  </body>
</html>
  1. 在WEB-INF下创建jsp文件夹,写其他视图
    allUser.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/1/14
  Time: 22:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>Title</title>
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>用户列表</small>
                </h1>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/user/toAddUser">新增</a>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody>
                <c:forEach var="user" items="${requestScope.get('list')}">
                    <tr>
                        <td>${user.getUserId()}</td>
                        <td>${user.getUserName()}</td>
                        <td>${user.getAge()}</td>
                        <td>${user.getSex()}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/user/getUserById?userId=${user.getUserId()}">更改</a> |
                            <a href="${pageContext.request.contextPath}/user/deleteUser/${user.getUserId()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

addUser.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>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增用户</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/user/addUser" method="post">
        姓名:<input type="text" name="userName"><br><br><br>
        年龄:<input type="text" name="age"><br><br><br>
        性别:<input type="text" name="sex"><br><br><br>
        <input type="submit" value="添加">
    </form>

</div>

updateUser.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>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改信息</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/user/updateUser" method="post">
        <input type="hidden" name="userId" value="${user.getUserId()}"/>
        姓名:<input type="text" name="userName" value="${user.getUserName()}"/>
        年龄:<input type="text" name="age" value="${user.getAge()}"/>
        性别:<input type="text" name="sex" value="${user.getSex() }"/>
        <input type="submit" value="提交"/>
    </form>

</div>

八,最终的项目结构如下

Spring+SpringMVC+Mybatis整合开发(超级详细)

九,启动tomcat测试

如启动时候遇到以下错误:org.apache.catalina.core.StandardContext.startInternal 由于之前的错误,Context[]启动失败,是因为Coetext加载jar失败导致,需手动创建lib包,然后手动添加依赖之后再启动
Spring+SpringMVC+Mybatis整合开发(超级详细)
Spring+SpringMVC+Mybatis整合开发(超级详细)
视图如下:
index.jsp
Spring+SpringMVC+Mybatis整合开发(超级详细)
allUser.jsp
Spring+SpringMVC+Mybatis整合开发(超级详细)

addUser.jsp
Spring+SpringMVC+Mybatis整合开发(超级详细)
updateUser.jsp
Spring+SpringMVC+Mybatis整合开发(超级详细)

版权声明:程序员胖胖胖虎阿 发表于 2022年10月21日 下午3:48。
转载请注明:Spring+SpringMVC+Mybatis整合开发(超级详细) | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...