SpringSpring五,(实战,非知识点)用一个简单的项目去理解SSM架构
白鹤忘机通过一个简单的项目案例整合[Spring+Mybatis+SpringMVC]
● Java
● Spring
● Spring
● SpringMVC
● Mybatis
(首字母缩写,SSM)
本片文章是对Spring+Mybatis+SpringMVC三框架的整合总结,将会通过一个简单的项目案例进行整合。
- 前言
本片文章是对Spring+Mybatis+SpringMVC三框架的整合总结,将会通过一个简单的项目案例进行整合。
1.1 MVC架构
先通过一张图回顾一下MVC架构模式:
● MVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范。
● MVC将业务逻辑、数据、视图分离的方法来组织代码。
● MVC主要作用是降低了视图与业务逻辑间的双向偶合。
● MVC不是一种设计模式,MVC是一种架构模式。不同的MVC存在差异。
Model层: 在模型层中又可以分为两层,即Service层和Dao层,这两层的主要功能是:
● Service层: 负责一些业务处理,比如说:获取数据库连接,关闭数据库连接,事务回滚或者一些复杂的逻辑业务处理
● Dao层:(Database Accept Object) 负责访问数据库,对数据的操作,获取结果集,将结果集中的数据装到OV(Object Value)对象中,之后再返回给Service层
Controller层:主要功能是接收用户请求,委托给模型进行处理(状态改变),处理完毕后把返回的模型数据返回给视图,由视图负责展示。也就是说控制器做了个调度员的工作。
View层:主要负责显示数据(Html、Css、jQuery等等),一般就是我们见到的用户界面,客户想看到的东西。
MVC框架要做哪些事情
- 将url映射到java类或java类的方法 .
- 封装用户提交的数据 .
- 处理请求–调用相关的业务处理–封装响应数据 .
- 将响应的数据进行渲染 . jsp / html 等表示层数据 .
1.2 项目最终效果图
这个简单项目的最终效果图如下:实现对书籍的增删改查功能
下面正式开整
- 开发环境准备
● IDEA2023极其以上
● MySQL (5.0)或者(8.0)
● Tomcat 9
● Maven 3.6.3
- 数据库表books
在forstudy数据库下,创建一个存放书籍数据的数据库表books表:
先创建一个数据库,名为forstudy ( 含义 “for study”一切都是为了学习!!!!!!!)
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,'从进门到进牢');
|
pom.xml
这里将会导入所有需要的依赖
SpringMVC
<groupId>cn.bithachi</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ssm-build</artifactId>
<dependencies> <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>
<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>
<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.6</version>
</dependency>
<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.2.11.RELEASE</version>
</dependency>
<dependency> <groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
<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>
|
5. 项目目录结构
这里直接显示最终的目录结构,我们将会在后面一步一步配置
6. IDEA之lib目录
我们最终所有的依赖都需要添加到lib目录中,否则会报错
7. resources
7.1 database.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/forstudy?useSSL=true&useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=123456
|
7.2 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>
|
7.3 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> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <package name="cn.bithachi.pojo"/> </typeAliases> <mappers> <mapper resource="cn/bithachi/dao/BookMapper.xml"/> </mappers> </configuration>
|
7.4 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:database.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="30"/> <property name="minPoolSize" value="10"/> <property name="autoCommitOnClose" value="false"/> <property name="checkoutTimeout" value="10000"/> <property name="acquireRetryAttempts" value="2"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="cn.bithachi.dao"/> </bean> </beans>
|
7.5 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 /> <mvc:default-servlet-handler/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <context:component-scan base-package="cn.bithachi.controller"/> </beans>
|
7.6 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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="cn.bithachi.service" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="BookServiceImpl" class="cn.bithachi.service.BookServiceImpl"> <property name="bookDao" ref="bookDao"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="delete" propagation="REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <tx:method name="search*" propagation="REQUIRED"/> <tx:method name="get" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="txPointcut" expression="execution(* cn.bithachi.dao.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans>
|
8. 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"> <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> <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-config> <session-timeout>15</session-timeout> </session-config> </web-app>
|
9. controller
BookController.java
package cn.bithachi.controller; import cn.bithachi.pojo.Books; import cn.bithachi.service.BookService; 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.RequestMapping; import java.util.ArrayList; import java.util.List; @SuppressWarnings("all") @Controller @RequestMapping("/book") public class BookController {
@Autowired @Qualifier("BookServiceImpl") private BookService bookService; @RequestMapping("/allBook") public String list(Model model) { List<Books> list = bookService.queryAllBook(); model.addAttribute("list", list); return "allBook"; } @RequestMapping("/toAddBook") public String toAddPaper() { return "addBook"; } @RequestMapping("/addBook") public String addPaper(Books books) { System.out.println(books); bookService.addBook(books); return "redirect:/book/allBook"; } @RequestMapping("/toUpdateBook") public String toUpdateBook(Model model, int id) { Books books = bookService.queryBookById(id); System.out.println(books); model.addAttribute("book", books); return "updateBook"; } @RequestMapping("/updateBook") public String updateBook(Model model, Books book) { System.out.println(book); bookService.updateBook(book); Books books = bookService.queryBookById(book.getBookID()); model.addAttribute("books", books); return "redirect:/book/allBook"; } @RequestMapping("/del/{bookId}") public String deleteBook(@PathVariable("bookId") int id) { bookService.deleteBookById(id); return "redirect:/book/allBook"; } @RequestMapping("/queryBook") public String queryBook(Model model, String bookName) { Books books = bookService.queryBookByName(bookName); List<Books> list = new ArrayList<Books>(); if (books!=null){ list.add(books); } model.addAttribute("list", list); return "allBook"; } }
|
10. dao
10.1 BookDao.java
package cn.bithachi.dao; import cn.bithachi.pojo.Books; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @SuppressWarnings("all") public interface BookDao { int addBook(Books book); int deleteBookById(int id); int updateBook(Books books); Books queryBookById(int id); List<Books> queryAllBook(); Books queryBookByName(@PathVariable("bookName") String bookName); }
|
10.2 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="cn.bithachi.dao.BookDao"> <insert id="addBook" parameterType="Books"> insert into books(bookName,bookCounts,detail) values (#{bookName}, #{bookCounts}, #{detail}) </insert> <delete id="deleteBookById" parameterType="int"> delete from books where bookID=#{bookID} </delete> <update id="updateBook" parameterType="Books"> update books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} where bookID = #{bookID} </update> <select id="queryBookById" resultType="Books"> select * from books where bookID = #{bookID} </select> <select id="queryAllBook" resultType="Books"> SELECT * from books </select> <select id="queryBookByName" resultType="Books"> SELECT * from books where bookName=#{bookName} </select> </mapper>
|
11. pojo
Books.java
package cn.bithachi.pojo; @SuppressWarnings("all") public class Books { private int bookID; 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; } 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; } @Override public String toString() { return "Books{" + "bookID=" + bookID + ", bookName='" + bookName + '\'' + ", bookCounts=" + bookCounts + ", detail='" + detail + '\'' + '}'; } }
|
12. service
12.1 BookService.java
package cn.bithachi.service; import cn.bithachi.pojo.Books; import java.util.List; @SuppressWarnings("all")
public interface BookService { int addBook(Books book); int deleteBookById(int id); int updateBook(Books books); Books queryBookById(int id); List<Books> queryAllBook(); Books queryBookByName(String bookName); }
|
12.2 BookServiceImpl.java
package cn.bithachi.service; import cn.bithachi.dao.BookDao; import cn.bithachi.pojo.Books; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @SuppressWarnings("all") @Service public class BookServiceImpl implements BookService { private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public int addBook(Books book) { return bookDao.addBook(book); } public int deleteBookById(int id) { return bookDao.deleteBookById(id); } public int updateBook(Books books) { return bookDao.updateBook(books); } public Books queryBookById(int id) { return bookDao.queryBookById(id); } public List<Books> queryAllBook() { return bookDao.queryAllBook(); } public Books queryBookByName(String bookName){ return bookDao.queryBookByName(bookName); } }
|
13. jsp
13.1 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE HTML> <html> <head> <title>首页</title> <style type="text/css"> a { text-decoration: none; color: black; font-size: 18px; } h3 { width: 180px; height: 38px; margin: 100px auto; text-align: center; line-height: 38px; background: deepskyblue; border-radius: 4px; } </style> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a> </h3> </body> </html>
|
13.2 allBook.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"> <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> <div class="row"> <div class="col-md-4 column" style="float: left;"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示所有书籍</a> </div> <div class="col-md-4 column" style="float: right;"> <form action="${pageContext.request.contextPath}/book/queryBook" method="post" > <input type="text" name="bookName" placeholder="请输入要查询的书籍名称" > <input type="submit" value="查询" class="btn btn-primary"> </form> </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="book" items="${requestScope.get('list')}"> <tr> <td>${book.getBookID()}</td> <td>${book.getBookName()}</td> <td>${book.getBookCounts()}</td> <td>${book.getDetail()}</td> <td> <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> | <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body>
|
13.3 addBook.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"> <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}/book/addBook" method="post"> 书籍名称:<input type="text" name="bookName" ><br><br><br> 书籍数量:<input type="text" name="bookCounts"><br><br><br> 书籍详情:<input type="text" name="detail"><br><br><br> <input type="submit" value="添加"> </form> </div>
|
13.4 updateBook.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"> <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}/book/updateBook" method="post"> <input type="hidden" name="bookID" value="${book.getBookID()}"/> 书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/> 书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/> 书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/> <input type="submit" value="提交"/> </form> </div>
|
白鹤忘机
观看和感受正在经历的事物本相,而不是其名称。 ---艾伦·瓦兹-
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 白鹤忘机!