欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring+SpringMVC+MyBatis整合

程序员文章站 2022-04-14 18:58:31
概述前文记录了Spring MVC的常用功能和MyBatis的基本用法。在实际的项目开发中,需要进行整合,从而使用Spring的依赖注入来减少代码的耦合,使用Spring MVC处理请求并作出响应,使用MyBatis完成数据库操作。数据准备在前文创建的mybatis数据库中删除表tb_user重新创... ......

概述
前文记录了spring mvc的常用功能和mybatis的基本用法。在实际的项目开发中,需要进行整合,从而使用spring的依赖注入来减少代码的耦合,使用spring mvc处理请求并作出响应,使用mybatis完成数据库操作。
数据准备
在前文创建的mybatis数据库中删除表tb_user重新创建该表,同时新建一张表tb_book,表设计和测试数据如下:

创建/配置项目
创建项目的步骤此处不再赘述,与springmvc创建相同(前文链接https://www.cnblogs.com/dcl-snow/p/11444751.html)。
项目目录结构如图:

打开项目的pom文件,添加spring、spring mvc、mybatis和连接mysql数据库的包依赖:

  1 <?xml version="1.0" encoding="utf-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  4           xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <modelversion>4.0.0</modelversion>
  6 
  7     <groupid>com.snow</groupid>
  8     <artifactid>ssmbookproject</artifactid>
  9     <version>1.0-snapshot</version>
 10     <packaging>war</packaging>
 11 
 12     <name>ssmbookproject maven webapp</name>
 13     <!-- fixme change it to the project's website -->
 14     <url>http://www.example.com</url>
 15 
 16     <properties>
 17         <project.build.sourceencoding>utf-8</project.build.sourceencoding>
 18         <maven.compiler.source>1.7</maven.compiler.source>
 19         <maven.compiler.target>1.7</maven.compiler.target>
 20         <!-- spring版本号 -->
 21         <spring.version>4.3.10.release</spring.version>
 22         <!-- mybatis版本号 -->
 23         <mybatis.version>3.4.6</mybatis.version>
 24      </properties>
 25 
 26     <dependencies>
 27         <dependency>
 28             <groupid>junit</groupid>
 29             <artifactid>junit</artifactid>
 30             <version>4.11</version>
 31             <scope>test</scope>
 32         </dependency>
 33         <!-- 数据库 -->
 34         <dependency>
 35             <groupid>mysql</groupid>
 36             <artifactid>mysql-connector-java</artifactid>
 37             <version>5.1.37</version>
 38             <scope>runtime</scope>
 39         </dependency>
 40         <dependency>
 41             <!--jdbc连接池-->
 42             <groupid>c3p0</groupid>
 43             <artifactid>c3p0</artifactid>
 44             <version>0.9.1.2</version>
 45         </dependency>
 46         <!-- dao: mybatis -->
 47         <dependency>
 48             <groupid>org.mybatis</groupid>
 49             <artifactid>mybatis</artifactid>
 50             <version>3.3.0</version>
 51         </dependency>
 52         <dependency>
 53             <groupid>org.mybatis</groupid>
 54             <artifactid>mybatis-spring</artifactid>
 55             <version>1.2.3</version>
 56         </dependency>
 57         <!-- servlet web -->
 58         <dependency>
 59             <groupid>taglibs</groupid>
 60             <artifactid>standard</artifactid>
 61             <version>1.1.2</version>
 62         </dependency>
 63         <dependency>
 64             <groupid>jstl</groupid>
 65             <artifactid>jstl</artifactid>
 66             <version>1.2</version>
 67         </dependency>
 68         <!--gson-->
 69         <dependency>
 70             <groupid>com.google.code.gson</groupid>
 71             <artifactid>gson</artifactid>
 72             <version>2.8.2</version>
 73         </dependency>
 74         <dependency>
 75             <groupid>javax.servlet</groupid>
 76             <artifactid>javax.servlet-api</artifactid>
 77             <version>3.1.0</version>
 78         </dependency>
 79         <dependency>
 80             <groupid>org.springframework</groupid>
 81             <artifactid>spring-core</artifactid>
 82             <version>${spring.version}</version>
 83         </dependency>
 84         <dependency>
 85             <groupid>org.springframework</groupid>
 86             <artifactid>spring-beans</artifactid>
 87             <version>${spring.version}</version>
 88         </dependency>
 89         <dependency>
 90             <groupid>org.springframework</groupid>
 91             <artifactid>spring-context</artifactid>
 92             <version>${spring.version}</version>
 93         </dependency>
 94         <dependency>
 95             <groupid>org.springframework</groupid>
 96             <artifactid>spring-jdbc</artifactid>
 97             <version>${spring.version}</version>
 98         </dependency>
 99         <dependency>
100             <groupid>org.springframework</groupid>
101             <artifactid>spring-tx</artifactid>
102             <version>${spring.version}</version>
103         </dependency>
104         <dependency>
105             <groupid>org.springframework</groupid>
106             <artifactid>spring-web</artifactid>
107             <version>${spring.version}</version>
108         </dependency>
109         <dependency>
110             <groupid>org.springframework</groupid>
111             <artifactid>spring-webmvc</artifactid>
112             <version>${spring.version}</version>
113         </dependency>
114         <dependency>
115             <groupid>org.springframework</groupid>
116             <artifactid>spring-test</artifactid>
117             <version>${spring.version}</version>
118         </dependency>
119         <dependency>
120             <groupid>org.projectlombok</groupid>
121             <artifactid>lombok</artifactid>
122             <version>1.16.22</version>
123         </dependency>
124     </dependencies>
125 
126     <build>
127         <finalname>bookproj</finalname>
128         <pluginmanagement><!-- lock down plugins versions to avoid using maven defaults (may be moved to parent pom) -->
129             <plugins>
130                 <plugin>
131                     <artifactid>maven-clean-plugin</artifactid>
132                     <version>3.1.0</version>
133                 </plugin>
134                 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#plugin_bindings_for_war_packaging -->
135                 <plugin>
136                     <artifactid>maven-resources-plugin</artifactid>
137                     <version>3.0.2</version>
138                 </plugin>
139                 <plugin>
140                     <artifactid>maven-compiler-plugin</artifactid>
141                     <version>3.8.0</version>
142                 </plugin>
143                 <plugin>
144                     <artifactid>maven-surefire-plugin</artifactid>
145                     <version>2.22.1</version>
146                 </plugin>
147                 <plugin>
148                     <artifactid>maven-war-plugin</artifactid>
149                     <version>3.2.2</version>
150                 </plugin>
151                 <plugin>
152                     <artifactid>maven-install-plugin</artifactid>
153                     <version>2.5.2</version>
154                 </plugin>
155                 <plugin>
156                     <artifactid>maven-deploy-plugin</artifactid>
157                     <version>2.8.2</version>
158                 </plugin>
159             </plugins>
160         </pluginmanagement>
161     </build>
162 </project>


在项目的resources目录下创建jdbc.properties文件,编写如下内容:

  1 jdbc.driver=com.mysql.jdbc.driver
  2 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useunicode=true&characterencoding=utf8
  3 jdbc.username=root
  4 #“****”是mysql数据库密码
  5 jdbc.password=****
  6 #最大连接数
  7 maxpoolsize=20
  8 #最小连接数
  9 minpoolsize=10
 10 #连接超时时间
 11 checkouttimeout=60000
 12 #失败重连次数
 13 acquireretryattempts=3

在项目的resources目录下创建applicationcontext.xml文件,编写如下内容:
  1 <?xml version="1.0" encoding="utf-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans"
  3        xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  4        xmlns:context="http://www.springframework.org/schema/context"
  5        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/tx http://www.springframework.org/schema/tx/springtx.xsd">
  6 
  7     <!--配合mybatis-->
  8     <!--数据库配置文件-->
  9     <context:property-placeholder location="classpath:jdbc.properties"/>
 10     <!--数据库连接池-->
 11     <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
 12         <!--配置连接池属性-->
 13         <property name="driverclass" value="${jdbc.driver}"/>
 14         <property name="jdbcurl" value="${jdbc.url}"/>
 15         <property name="user" value="${jdbc.username}"/>
 16         <property name="password" value="${jdbc.password}"/>
 17         <property name="maxpoolsize" value="${maxpoolsize}"/>
 18         <property name="minpoolsize" value="${minpoolsize}"/>
 19         <property name="autocommitonclose" value="false"/>
 20         <property name="checkouttimeout" value="${checkouttimeout}"/>
 21         <property name="acquireretryattempts" value="${acquireretryattempts}"/>
 22     </bean>
 23     <!-- 配置 sqlsessionfactory 对象-->
 24     <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
 25         <!--注入数据库连接池-->
 26         <property name="datasource" ref="datasource"/>
 27         <!--  mybaties 配置⽂件 -->
 28         <property name="configlocation" value="classpath:mybatis-config.xml"/>
 29         <!-- 扫描mapper 需要的 xml ⽂件 -->
 30         <property name="mapperlocations" value="classpath:mapper/*.xml"/>
 31     </bean>
 32     <!-- 配置扫描 mapper 接⼝包, 动态实现 mapper 接⼝, 注⼊到 spring 容器中 -->
 33     <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
 34         <!-- 注⼊ sqlsessionfactory -->
 35         <property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/>
 36         <!-- 给出需要扫描 mapper 接⼝包 -->
 37         <property name="basepackage" value="com.snow.mapper"/>
 38     </bean>
 39     <!--spring-service-->
 40     <!-- 扫描 service 包下所有使⽤注解的类型 -->
 41     <context:component-scan base-package="com.snow.service"/>
 42     <!-- 配置事务管理器 -->
 43     <bean id="transactionmanager"
 44           class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
 45         <!-- 注⼊数据库连接池 -->
 46         <property name="datasource" ref="datasource"/>
 47     </bean>
 48 </beans>


在项目的resources目录下创建springmvc-sevlet.xml文件,编写如下内容:

  1 <?xml version="1.0" encoding="utf-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans"
  3        xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  4        xmlns:p="http://www.springframework.org/schema/p"
  5        xmlns:context="http://www.springframework.org/schema/context"
  6        xmlns:mvc="http://www.springframework.org/schema/mvc"
  7        xsi:schemalocation="http://www.springframework.org/schema/beans
  8        http://www.springframework.org/schema/beans/spring-beans.xsd
  9        http://www.springframework.org/schema/mvc
 10        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 11        http://www.springframework.org/schema/context
 12        http://www.springframework.org/schema/context/spring-context.xsd">
 13 
 14     <!--spring可以自动扫描base-package设置的包或子包下的java类,如果扫描到有spring相关注解的类,则注册为spring的bean-->
 15     <context:component-scan base-package="com.snow.controller"/>
 16     <!-- 配置注解驱动 -->
 17     <mvc:annotation-driven/>
 18     <!-- 视图解析器 -->
 19     <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
 20         <!--前缀-->
 21         <property name="prefix" value="/web-inf/views/"/>
 22         <!--后缀-->
 23         <property name="suffix" value=".jsp"/>
 24     </bean>
 25     <!--静态资源默认servlet配置:1、加⼊对静态资源js、gif、png的处理;2、允许使⽤"/"做整体映射-->
 26     <mvc:default-servlet-handler/>
 27 </beans>


在项目的web.xml文件中编写如下内容:

  1 <!doctype web-app public
  2          "-//sun microsystems, inc.//dtd web application 2.3//en"
  3          "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4 <web-app>
  5     <display-name>ssmbookproject</display-name>
  6     <welcome-file-list>
  7         <welcome-file>login.jsp</welcome-file>
  8     </welcome-file-list>
  9     <!--spring mvc 配置并添加监听-->
 10     <context-param>
 11         <param-name>contextconfiglocation</param-name>
 12         <param-value>classpath:applicationcontext.xml</param-value>
 13     </context-param>
 14     <!-- 字符过滤器 传值乱码-->
 15     <filter>
 16         <filter-name>encodingfilter</filter-name>
 17         <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
 18         <init-param>
 19             <param-name>encoding</param-name>
 20             <param-value>utf-8</param-value>
 21         </init-param>
 22     </filter>
 23     <filter-mapping>
 24         <filter-name>encodingfilter</filter-name>
 25         <url-pattern>/*</url-pattern>
 26     </filter-mapping>
 27     <listener>
 28         <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
 29     </listener>
 30     <!--配置前端控制器 进行请求分发 dispatcherservlet本质也是一个servlet -->
 31     <servlet>
 32         <!--名字可以自定义-->
 33         <servlet-name>springmvc</servlet-name>
 34         <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
 35         <init-param>
 36             <param-name>contextconfiglocation</param-name>
 37             <param-value>classpath:springmvc-sevlet.xml</param-value>
 38         </init-param>
 39         <!--标记容器启动的时候就启动这个servlet-->
 40         <load-on-startup>1</load-on-startup>
 41     </servlet>
 42     <servlet-mapping>
 43         <servlet-name>springmvc</servlet-name>
 44         <!--拦截所有-->
 45         <url-pattern>/</url-pattern>
 46     </servlet-mapping>
 47 </web-app>

程序开发
编写pojo
在com.snow.domain包中创建user.java类文件,编写如下程序:
  1 @data
  2 public class user implements serializable {
  3     private integer id;
  4     private string loginname;
  5     private string password;
  6     private string username;
  7     private string phone;
  8     private string address;
  9 }

再创建book.java类文件,编写如下程序:
  1 @data
  2 public class book implements serializable {
  3     private integer id;
  4     private string name;
  5     private string author;
  6     private string publication;
  7     private date publicationdate;
  8     private double price;
  9     private string image;
 10     private string remark;
 11 }

编写mapper接口
在com.snow.mapper包中创建usermapper.java接口文件,编写如下程序:
  1 public interface usermapper {
  2     user findwithloginnameandpassword(@param("loginname") string loginname, @param("password") string password);
  3 }

再创建bookmapper.java接口文件,编写如下程序:
  1 public interface bookmapper {
  2     list<book> findall();
  3 }

编写service和serviceimpl
在com.snow.service包中创建userservice.java接口文件,编写如下程序:
  1 public interface userservice {
  2     user login(string loginname, string password);
  3 }

再创建bookservice.java接口文件,编写如下程序:
  1 public interface bookservice {
  2     list<book> getall();
  3 }

在com.snow.service.impl包中创建userserviceimpl.java类文件,编写如下程序:
  1 @service
  2 public class userserviceimpl implements userservice {
  3     @autowired
  4     private usermapper usermapper;
  5 
  6     @override
  7     public user login(string loginname, string password){
  8         return usermapper.findwithloginnameandpassword(loginname,password);
  9     }
 10 }


再创建bookserviceimpl.java类文件,编写如下程序:

  1 @service
  2 public class bookserviceimpl implements bookservice {
  3     @autowired
  4     private bookmapper bookmapper;
  5     @override
  6     public list<book> getall(){
  7         return bookmapper.findall();
  8     }
  9 }

编写controller
在com.snow.controller包中创建usercontroller.java类文件,编写如下程序:
  1 @controller
  2 public class usercontroller {
  3     @autowired
  4     private userservice userservice;
  5 
  6     @requestmapping(value = "/login")
  7     public modelandview login(string loginname, string password, modelandview modelandview, httpsession httpsession) {
  8         user user = userservice.login(loginname, password);
  9         if (user != null) {
 10             httpsession.setattribute("user", user);
 11             modelandview.setview(new redirectview("main"));
 12        } else {
 13             modelandview.setviewname("error");
 14        }
 15         return modelandview;
 16     }
 17 }


再创建bookcontroller.java类文件,编写如下程序:

  1 @controller
  2 public class bookcontroller {
  3 
  4     @autowired
  5     private bookservice bookservice;
  6 
  7     @requestmapping(value = "/main")
  8     public string main(model model) {
  9         list<book> booklist = bookservice.getall();
 10         model.addattribute("booklist", booklist);
 11         return "main";
 12     }
 13 }


编写映射文件
在项目的resources目录下创建mapper目录,在目录中创建usermapper.xml,编写如下内容:

  1 <?xml version="1.0" encoding="utf-8" ?>
  2 <!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 <mapper namespace="com.snow.mapper.usermapper">
  4     <resultmap id="baseresultmap" type="com.snow.domain.user">
  5         <id column="id" property="id" jdbctype="integer"/>
  6         <result column="loginname" property="loginname" jdbctype="varchar"/>
  7         <result column="password" property="password" jdbctype="varchar"/>
  8         <result column="username" property="username" jdbctype="varchar"/>
  9         <result column="phone" property="phone" jdbctype="varchar"/>
 10         <result column="address" property="address" jdbctype="varchar"/>
 11     </resultmap>
 12     <sql id="base_column_list">
 13     id, loginname, password, username, phone, address
 14     </sql>
 15     <select id="findwithloginnameandpassword" resultmap="baseresultmap" parametertype="java.lang.string">
 16         select
 17         <include refid="base_column_list"/>
 18         from tb_user
 19         where loginname = #{loginname,jdbctype=varchar}
 20         and password = #{password,jdbctype=varchar}
 21     </select>
 22 </mapper>

再创建bookmapper.xml,编写如下内容:
  1 <?xml version="1.0" encoding="utf-8" ?>
  2 <!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 <mapper namespace="com.snow.mapper.bookmapper">
  4     <resultmap id="baseresultmap" type="com.snow.domain.book">
  5         <id column="id" property="id" jdbctype="integer"/>
  6         <result column="name" property="name" jdbctype="varchar"/>
  7         <result column="author" property="author" jdbctype="varchar"/>
  8         <result column="publicationdate" property="publicationdate" jdbctype="date"/>
  9         <result column="publication" property="publication" jdbctype="varchar"/>
 10         <result column="price" property="price" jdbctype="double"/>
 11         <result column="image" property="image" jdbctype="varchar"/>
 12         <result column="remark" property="remark" jdbctype="varchar"/>
 13     </resultmap>
 14     <sql id="base_column_list">
 15     id, name, author, publicationdate, publication, price, image, remark
 16     </sql>
 17     <select id="findall" resultmap="baseresultmap" parametertype="com.snow.domain.book">
 18         select
 19         <include refid="base_column_list"/>
 20         from tb_book
 21     </select>
 22  </mapper>

编写页面
在项目的webapp目录下创建images目录,将数据库中书的封面图和页面的背景图放在该目录下:

在项目的webapp目录下,创建base.css文件,编写如下程序:
  1 body{
  2     background-image: url(images/backimage.jpg);
  3     background-size:cover;
  4 }

在项目的webapp目录下,创建login.jsp文件,编写如下程序:
  1 <%--
  2   created by intellij idea.
  3   user: dcl_snow
  4   date: 2019/10/25
  5   time: 10:00
  6   to change this template use file | settings | file templates.
  7 --%>
  8 <%@ page contenttype="text/html;charset=utf-8" language="java" %>
  9 <html>
 10 <head>
 11     <title>登录页面</title>
 12     <link rel="stylesheet" type="text/css" href="base.css"/>
 13 </head>
 14 <body>
 15 <center>
 16     <h3>登录页面</h3>
 17     <form action="login" method="post">
 18         <table>
 19             <tr>
 20                 <td><label>登录名:</label></td>
 21                 <td><input type="text" id="loginname" name="loginname"></td>
 22             </tr>
 23             <tr>
 24                 <td><label>密&nbsp;&nbsp;&nbsp;&nbsp;码:</label></td>
 25                 <td><input type="password" id="password" name="password"></td>
 26             </tr>
 27             <tr>
 28                 <td><input type="submit" value="登录"></td>
 29             </tr>
 30         </table>
 31     </form>
 32 </center>
 33 </body>
 34 </html>

在项目的web-inf目录下,创建views目录,在该目录下创建main.jsp文件,编写如下程序:
  1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2 <%--
  3   created by intellij idea.
  4   user: dcl_snow
  5   date: 2019/10/25
  6   time: 10:00
  7   to change this template use file | settings | file templates.
  8 --%>
  9 <%@ page iselignored="false" %>
 10 <%@ page contenttype="text/html;charset=utf-8" language="java" %>
 11 <html>
 12 <head>
 13     <title>首页</title>
 14     <link rel="stylesheet" type="text/css" href="base.css"/>
 15 </head>
 16 <body>
 17 <center>
 18     欢迎[${sessionscope.user.username}]
 19     <table border="1">
 20         <tr>
 21             <th>书名</th>
 22             <th>封面</th>
 23             <th>作者</th>
 24             <th>价格</th>
 25         </tr>
 26         <c:foreach items="${requestscope.booklist}" var="book">
 27             <tr>
 28                 <td>${book.name}</td>
 29                 <td><img src="images/${book.image}" height="200"></td>
 30                 <td>${book.author}</td>
 31                 <td>${book.price}</td>
 32             </tr>
 33         </c:foreach>
 34     </table>
 35 </center>
 36 </body>
 37 </html>

再创建error.jsp文件,编写如下程序:
  1 <%--
  2   created by intellij idea.
  3   user: dcl_snow
  4   date: 2019/10/25
  5   time: 10:00
  6   to change this template use file | settings | file templates.
  7 --%>
  8 <%@ page contenttype="text/html;charset=utf-8" language="java" %>
  9 <html>
 10 <head>
 11     <title>错误页面</title>
 12     <link rel="stylesheet" type="text/css" href="base.css"/>
 13 </head>
 14 <body>
 15 <center>
 16     <h1><font color="red">用户名或密码错误!</font></h1>
 17 </center>
 18 </body>
 19 </html>

配置tomcat
为项目配置tomcat后,启动,浏览器访问:)。
登录页面:

输入错误的用户名或密码:

输入正确的用户名和密码: