SSM框架整合
项目结构:
SSM整合顺序:
1.dao层: 数据库,mybatis层的编写
2.Spring层:主要是spring整合mybatis
3.SpringMVC层:主要处理前后端的交互
1.创建数据库环境
创建一个存放书籍数据的数据库表
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
2.导入maven 相关的依赖包
在这里 <dependencies>
<!--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.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>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<!-- 文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.14</version>
<scope>test</scope>
</dependency>
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!-- jsr303校验包 -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>
</dependencies>
<!-- mybatis静态资源过滤的问题 -->
<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>
插入代码片
3.创建对应的包、基本的结构框架
- com.controller
- com.dao
- com.pojo
- com.service
4.编写对应的实体类
package com.pojo;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
public class Books {
private int bookID;
@NotEmpty(message = "书名不为空")
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
5.编写配置文件
全局配置文件 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
1.mybatis层
1.数据库连接database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
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.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.dao.BookMapper"></mapper>
</mappers>
</configuration>
编写Dao层的 bookMapper接口
package com.dao;
import com.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.awt.print.Book;
import java.util.List;
public interface BookMapper {
//获取所有的图书
List<Books> getAllBook();
//根据id获取书籍
Books getBookById(@Param("bookID") int bookID);
//添加一个书籍
int addBook(Books book);
//更新一个书籍
int updateBook(Books book);
//删除指定id的书籍
int deleteBookById(@Param("bookID") int bookID) ;
}
编写编写接口对应的 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.dao.BookMapper">
<select id="getAllBook" resultType="Books">
select * from books
</select>
<select id="getBookById" resultType="Books">
select * from books where bookID=#{bookID}
</select>
<update id="addBook" parameterType="Books">
insert into books (bookName,bookCounts,detail) values(#{bookName},#{bookCounts},#{detail})
</update>
<update id="updateBook" parameterType="Books">
update books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
</update>
<delete id="deleteBookById" parameterType="int">
delete from books where bookID=#{bookID}
</delete>
</mapper>
2.service层
bookService接口:
package com.service;
import com.pojo.Books;
import java.util.List;
public interface BookService {
List<Books> getAllBook();
Books getBookById(int bookID);
int updateBook(Books book);
int addBook(Books book);
int deleteBookById(int bookId);
}
bookServiceIm接口实现类
package com.service;
import com.dao.BookMapper;
import com.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class BookServiceIm implements BookService {
@Autowired
private BookMapper bookMapper;
public BookMapper getBookMapper() {
return bookMapper;
}
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public List<Books> getAllBook() {
return bookMapper.getAllBook();
}
public Books getBookById(int bookID) {
return bookMapper.getBookById(bookID);
}
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int bookId) {
return bookMapper.deleteBookById(bookId);
}
}
mybatis完成。。
1.spring层
spring整合mybatis,database.peoperties配置文件–.数据库连接池datasource---->注入sqlSessionfactoryBean,MapperScannerConfigurer将dao层导入spring中,交给spring管理
编写配置文件 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">
<!--导入 database.peoperties配置文件-->
<context:property-placeholder location="classpath:database.properties"></context:property-placeholder>
<!--数据库连接池 c3p0p-->
<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}"/>
</bean>
<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" >
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.dao"/>
</bean>
</beans>
2.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">
<context:component-scan base-package="com.service"/>
<bean id="bookServiceIm" class="com.service.BookServiceIm">
<property name="bookMapper" ref="bookMapper"></property>
</bean>
<!--事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
spring整合完成
3. SpringMVC层
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">
<!--字符过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- RESTful风格 —_method方法 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- ajax put请求获取参数问题-->
<filter>
<filter-name>HttpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- DispatcherServlet前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springMVC.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">
<!--扫描包-->
<context:component-scan base-package="com.controller"/>
<!-- 开启注解驱动-->
<mvc:annotation-driven/>
<!-- 开启静态资源扫描-->
<mvc:default-servlet-handler/>
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--thymeleafView视图解析器-->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
</beans>
全局配置文件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"
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-Service.xml"/>
<import resource="Spring-MVC.xml"/>
</beans>
配置结束
编写controller层
bookController
package com.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pojo.Books;
import com.pojo.Msg;
import com.service.BookServiceIm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@Controller
public class BookController {
@Autowired
private BookServiceIm bookServiceIm;
@RequestMapping(value = "/books", method = RequestMethod.GET)
public String getBooks(Model model, Integer pn) {
PageHelper.startPage(1, 5);
List<Books> bookList = bookServiceIm.getAllBook();
PageInfo page = new PageInfo(bookList);
model.addAttribute("PageInfo", page);
model.addAttribute("bookList", bookList);
return "bookList";
}
}
编写前端页面:bookList.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" th:src="@{/static/js/jquery-1.12.4.min.js}"></script>
<link th:href="@{/static/bootstrap-3.3.7-dist/css/bootstrap.min.css }" rel="stylesheet">
<script th:src="@{/static/bootstrap-3.3.7-dist/js/bootstrap.min.js}"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>SSM-CRUD</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button class="btn btn-primary">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<tr>
<th>bookId</th>
<th>bookName</th>
<th>bookCounts</th>
<th>detail</th>
<th>操作</th>
</tr>
<tr th:each=" book : ${pageInfo.list}">
<td th:text="${book.bookID}"></td>
<td th:text="${book.bookName}"></td>
<td th:text="${book.bookCounts}"></td>
<td th:text="${book.detail}"></td>
<td>
<button class="btn btn-primary btn-sm">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
新增</button>
<button class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
删除</button>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-6" th:text="'当前地'+${pageInfo.pageNum}+'页,共有'+${pageInfo.pages}+'页共计'+${pageInfo.total}+'条记录'">
</div>
<div class="col-md-6">
<nav aria-label="Page navigation">
<ul class="pagination" >
<li>
<a th:href="@{/testlist(pn=1)}" >首页</a>
</li>
<li th:if="${pageInfo.hasPreviousPage}">
<a th:href="@{/testlist(pn=${pageInfo.prePage})}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li th:each=" pageNum:${pageInfo.navigatepageNums}" th:if="${pageInfo}">
<a th:href="@{'/testlist?pn='+${pageNum} }" th:text="${pageNum}" th:if="${pageNum!=pageInfo.pageNum}"></a>
<span style="font-weight: bold;background: #6faed9;" th:if="${pageNum == pageInfo.pageNum}" th:text="${pageNum}" ></span>
</li>
<!-- <li th:each="nav:${pageInfo.navigatepageNums}">-->
<!-- <a th:href="'/usermanage?pageNum='+${nav}" th:text="${nav}" th:if="${nav != pageInfo.pageNum}"></a>-->
<!-- <span style="font-weight: bold;background: #6faed9;" th:if="${nav == pageInfo.pageNum}" th:text="${nav}" ></span>-->
<!-- </li>-->
<li th:if="${pageInfo.hasNextPage}">
<a th:href="@{testlist(pn=${pageInfo.nextPage})}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
<li >
<a th:href="@{/testlist(pn=${pageInfo.pages})}" >尾页</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
完结撒花…