概述
前文记录了Spring MVC的常用功能和MyBatis的基本用法。在实际的项目开发中,需要进行整合,从而使用Spring的依赖注入来减少代码的耦合,使用Spring MVC处理请求并作出响应,使用MyBatis完成数据库操作。
数据准备
在前文创建的mybatis数据库中删除表tb_user重新创建该表,同时新建一张表tb_book,表设计和测试数据如下:
创建/配置项目
创建项目的步骤此处不再赘述,与SpringMVC创建相同(前文链接:https://www.jianshu.com/p/fde4557c527c)。
项目目录结构如图:
打开项目的pom文件,添加Spring、Spring MVC、Mybatis和连接MySQL数据库的包依赖:
<?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>com.snow</groupId>
<artifactId>ssmbookproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssmbookproject Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!-- spring版本号 -->
<spring.version>4.3.10.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.4.6</mybatis.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
<scope>runtime</scope>
</dependency>
<dependency>
<!--jdbc连接池-->
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- DAO: MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- Servlet web -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
</dependencies>
<build>
<finalName>bookproj</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
在项目的resources目录下创建jdbc.properties文件,编写如下内容:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username=root
#“****”是mysql数据库密码
jdbc.password=****
#最大连接数
maxPoolSize=20
#最小连接数
minPoolSize=10
#连接超时时间
checkoutTimeout=60000
#失败重连次数
acquireRetryAttempts=3
在项目的resources目录下创建applicationContext.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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/springtx.xsd">
<!--配合MyBatis-->
<!--数据库配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据库连接池-->
<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}"/>
<property name="maxPoolSize" value="${maxPoolSize}"/>
<property name="minPoolSize" value="${minPoolSize}"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="${checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
</bean>
<!-- 配置 SqlSessionFactory 对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!-- MyBaties 配置⽂件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 扫描mapper 需要的 xml ⽂件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置扫描 mapper 接⼝包, 动态实现 mapper 接⼝, 注⼊到 Spring 容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注⼊ sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描 mapper 接⼝包 -->
<property name="basePackage" value="com.snow.mapper"/>
</bean>
<!--spring-service-->
<!-- 扫描 service 包下所有使⽤注解的类型 -->
<context:component-scan base-package="com.snow.service"/>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注⼊数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
在项目的resources目录下创建springmvc-sevlet.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:p="http://www.springframework.org/schema/p"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--spring可以自动扫描base-package设置的包或子包下的java类,如果扫描到有spring相关注解的类,则注册为spring的bean-->
<context:component-scan base-package="com.snow.controller"/>
<!-- 配置注解驱动 -->
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/views/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--静态资源默认servlet配置:1、加⼊对静态资源js、gif、png的处理;2、允许使⽤"/"做整体映射-->
<mvc:default-servlet-handler/>
</beans>
在项目的web.xml文件中编写如下内容:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>ssmbookproject</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!--Spring MVC 配置并添加监听-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 字符过滤器 传值乱码-->
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置前端控制器 进行请求分发 DispatcherServlet本质也是一个Servlet -->
<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:springmvc-sevlet.xml</param-value>
</init-param>
<!--标记容器启动的时候就启动这个servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!--拦截所有-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
程序开发
编写POJO
在com.snow.domain包中创建User.java类文件,编写如下程序:
@Data
public class User implements Serializable {
private Integer id;
private String loginname;
private String password;
private String username;
private String phone;
private String address;
}
再创建Book.java类文件,编写如下程序:
@Data
public class Book implements Serializable {
private Integer id;
private String name;
private String author;
private String publication;
private Date publicationdate;
private Double price;
private String image;
private String remark;
}
编写mapper接口
在com.snow.mapper包中创建UserMapper.java接口文件,编写如下程序:
public interface UserMapper {
User findWithLoginnameAndPassword(@Param("loginname") String loginname, @Param("password") String password);
}
再创建BookMapper.java接口文件,编写如下程序:
public interface BookMapper {
List<Book> findAll();
}
编写Service和ServiceImpl
在com.snow.service包中创建UserService.java接口文件,编写如下程序:
public interface UserService {
User login(String loginname, String password);
}
再创建BookService.java接口文件,编写如下程序:
public interface BookService {
List<Book> getAll();
}
在com.snow.service.impl包中创建UserServiceImpl.java类文件,编写如下程序:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User login(String loginname, String password){
return userMapper.findWithLoginnameAndPassword(loginname,password);
}
}
再创建BookServiceImpl.java类文件,编写如下程序:
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public List<Book> getAll(){
return bookMapper.findAll();
}
}
编写Controller
在com.snow.controller包中创建UserController.java类文件,编写如下程序:
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/login")
public ModelAndView login(String loginname, String password, ModelAndView modelAndView, HttpSession httpSession) {
User user = userService.login(loginname, password);
if (user != null) {
httpSession.setAttribute("user", user);
modelAndView.setView(new RedirectView("main"));
} else {
modelAndView.setViewName("error");
}
return modelAndView;
}
}
再创建BookController.java类文件,编写如下程序:
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping(value = "/main")
public String main(Model model) {
List<Book> bookList = bookService.getAll();
model.addAttribute("bookList", bookList);
return "main";
}
}
编写映射文件
在项目的resources目录下创建mapper目录,在目录中创建UserMapper.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.snow.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.snow.domain.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="loginname" property="loginname" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="phone" property="phone" jdbcType="VARCHAR"/>
<result column="address" property="address" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, loginname, password, username, phone, address
</sql>
<select id="findWithLoginnameAndPassword" resultMap="BaseResultMap" parameterType="java.lang.String">
select
<include refid="Base_Column_List"/>
from tb_user
where loginname = #{loginname,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>
</mapper>
再创建BookMapper.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.snow.mapper.BookMapper">
<resultMap id="BaseResultMap" type="com.snow.domain.Book">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="author" property="author" jdbcType="VARCHAR"/>
<result column="publicationdate" property="publicationdate" jdbcType="DATE"/>
<result column="publication" property="publication" jdbcType="VARCHAR"/>
<result column="price" property="price" jdbcType="DOUBLE"/>
<result column="image" property="image" jdbcType="VARCHAR"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, name, author, publicationdate, publication, price, image, remark
</sql>
<select id="findAll" resultMap="BaseResultMap" parameterType="com.snow.domain.Book">
select
<include refid="Base_Column_List"/>
from tb_book
</select>
</mapper>
编写页面
在项目的webapp目录下创建images目录,将数据库中书的封面图和页面的背景图放在该目录下:
在项目的webapp目录下,创建base.css文件,编写如下程序:
body{
background-image: url(images/backImage.jpg);
background-size:cover;
}
在项目的webapp目录下,创建login.jsp文件,编写如下程序:
<%--
Created by IntelliJ IDEA.
User: Dcl_Snow
Date: 2019/10/25
Time: 10:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
<link rel="stylesheet" type="text/css" href="base.css"/>
</head>
<body>
<center>
<h3>登录页面</h3>
<form action="login" method="post">
<table>
<tr>
<td><label>登录名:</label></td>
<td><input type="text" id="loginname" name="loginname"></td>
</tr>
<tr>
<td><label>密 码:</label></td>
<td><input type="password" id="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
在项目的WEB-INF目录下,创建views目录,在该目录下创建main.jsp文件,编写如下程序:
<%@ taglib prefix="C" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Dcl_Snow
Date: 2019/10/25
Time: 10:00
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="base.css"/>
</head>
<body>
<center>
欢迎[${sessionScope.user.username}]
<table border="1">
<tr>
<th>书名</th>
<th>封面</th>
<th>作者</th>
<th>价格</th>
</tr>
<C:forEach items="${requestScope.bookList}" var="book">
<tr>
<td>${book.name}</td>
<td><img src="images/${book.image}" height="200"></td>
<td>${book.author}</td>
<td>${book.price}</td>
</tr>
</C:forEach>
</table>
</center>
</body>
</html>
再创建error.jsp文件,编写如下程序:
<%--
Created by IntelliJ IDEA.
User: Dcl_Snow
Date: 2019/10/25
Time: 10:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误页面</title>
<link rel="stylesheet" type="text/css" href="base.css"/>
</head>
<body>
<center>
<h1><font color="red">用户名或密码错误!</font></h1>
</center>
</body>
</html>
配置Tomcat
为项目配置Tomcat后,启动,浏览器访问:http://localhost:8080/。
登录页面:
输入错误的用户名或密码:
输入正确的用户名和密码: