文章目录
一、SSM框架整合之Mybatis
-
创建项目
-
配置pom.xml
<?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.ola</groupId> <artifactId>ssm-build</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <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>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build> </project>
-
在java根目录创建包pojo、dao、service、controller
-
在resources根目录创建applicationContext.xml、mybatis-config.xml、database.properties
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="classpath:spring-service.xml"/> <import resource="classpath:spring-dao.xml"/> <import resource="classpath:spring-mvc.xml"/> </beans>
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="com.ola.pojo"/> </typeAliases> <mappers> <mapper class="com.ola.dao.BookMapper"/> </mappers> </configuration>
database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=niushijian
-
在dao中创建接口BookMapper
package com.ola.dao; import com.ola.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; /** * ClassName:BookMapper Package:com.ola.dao * * @author morningj * @date 2021/1/16 10:36 */ public interface BookMapper { int addBook(Books books); int deleteBookById(@Param("bid") int id); int updateBook(Books books); Books queryBookById(@Param("bid") int id); List<Books> queryAllBooks(); Books queryBookByName(@Param("name") String name); }
-
在dao中创建BookMapper.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.ola.dao.BookMapper"> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books(bookName, bookCounts, detail) VALUES (#{bookName}, #{bookCounts}, #{detail}) </insert> <delete id="deleteBookById" parameterType="int"> delete from ssmbuild.books where bookID = #{bid} </delete> <update id="updateBook" parameterType="Books"> update ssmbuild.books set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail} where bookID = #{bookID} </update> <select id="queryBookById" parameterType="int" resultType="Books"> select * from ssmbuild.books where bookID = #{bid} </select> <select id="queryAllBooks" resultType="Books"> select * from ssmbuild.books; </select> <select id="queryBookByName" resultType="Books"> select * from ssmbuild.books where bookName = #{name} </select> </mapper>
-
在mybatis-config.xml中绑定mapper
<mappers> <mapper class="com.ola.dao.BookMapper"/> </mappers>
-
在service中创建BookService接口(拷贝dao层的接口)
-
在service中创建接口实现类BookServiceImpl
package com.ola.service; import com.ola.dao.BookMapper; import com.ola.pojo.Books; import java.util.List; /** * ClassName:BookServiceImpl Package:com.ola.service * * @author morningj * @date 2021/1/16 10:53 */ public class BookServiceImpl implements BookService { // service层调用dao层 // 组合dao层 private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books books) { return bookMapper.addBook(books); } @Override public int deleteBookById(int id) { return bookMapper.deleteBookById(id); } @Override public int updateBook(Books books) { return bookMapper.updateBook(books); } @Override public Books queryBookById(int id) { return bookMapper.queryBookById(id); } @Override public List<Books> queryAllBooks() { return bookMapper.queryAllBooks(); } @Override public Books queryBookByName(String name) { return bookMapper.queryBookByName(name); } }
二、SSM框架整合之Spring
-
整合dao层,在resources根目录创建spring-dao.xml(关联数据库配置文件、连接池、SqlSessionFactory、dao接口扫描包)
<?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}"/> <!--c3p0连接池的私有属性--> <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> <!--SQLSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!--配置dao接口扫描包,动态实现Dao接口可以注入到Spring容器中--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 扫描dao包 --> <property name="basePackage" value="com.ola.dao"/> </bean> </beans>
-
整合service层,在resources根目录创建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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service下的包 --> <context:component-scan base-package="com.ola.service"/> <!-- 将所有的业务类注入到Spring中,可以通过配置或者注解实现 --> <bean id="BookServiceImpl" class="com.ola.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!-- 声明式事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- AOP事务支持 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* com.ola.dao.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>
三、SSM框架整合之SpringMVC
-
给项目添加web框架支持
-
配置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"> <!-- DispatcherServlet --> <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:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</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>
-
在resources根目录中创建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"> <!-- 使用扫描机制扫描控制器类,控制器类都在controller包及其子包下 --> <context:component-scan base-package="com.ola.controller"/> <!-- 过滤 --> <mvc:default-servlet-handler/> <!-- 配置映射器和适配器驱动 --> <mvc:annotation-driven/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
四、业务开始(增删改查)
-
创建BookController
package com.ola.controller; import com.ola.pojo.Books; import com.ola.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.RequestMapping; import java.util.ArrayList; import java.util.List; /** * ClassName:BookController Package:com.ola.controller * * @author morningj * @date 2021/1/16 11:34 */ @Controller @RequestMapping("/book") public class BookController { @Autowired @Qualifier("BookServiceImpl") private BookService bookService; @RequestMapping("/allBook") public String list(Model model) { List<Books> books = bookService.queryAllBooks(); model.addAttribute("books", books); return "allBook"; } @RequestMapping("/toAddBook") public String toAddPaper(Books books, Model model) { return "addBook"; } @RequestMapping("/addBook") public String addBook(Books books) { bookService.addBook(books); return "redirect:/book/allBook"; } @RequestMapping("/toUpdate") public String toUpdatePaper(int id, Model model) { Books books = bookService.queryBookById(id); model.addAttribute("books", books); return "updateBook"; } @RequestMapping("/updateBook") public String updatePaper(Books books) { bookService.updateBook(books); return "redirect:/book/allBook"; } @RequestMapping("/deleteBook") public String detetePaper(int id) { bookService.deleteBookById(id); return "redirect:/book/allBook"; } @RequestMapping("/queryBook") public String queryBook(String queryBookName, Model model) { Books books2 = bookService.queryBookByName(queryBookName); List<Books> books = new ArrayList<>(); books.add(books2); if (books2 == null) { books = bookService.queryAllBooks(); } model.addAttribute("books", books); return "allBook"; } }
-
前端代码
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- jQuery文件。务必在bootstrap.min.js 之前引入 --> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <title>首页</title> <style> button { height: 260px; width: 180px; align-content: center; } </style> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook"> <button class="btn btn-primary">查看全部书籍 </button> </a> </h3> </body> </html>
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> <!-- 新 Bootstrap 核心 CSS 文件 --> <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- jQuery文件。务必在bootstrap.min.js 之前引入 --> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> </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 class="row"> <div class="col-md-4 column"> <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"></div> <div class="col-md-4 column"> <form action="${pageContext.request.contextPath}/book/queryBook" method="post" class="form-inline"> <input type="text" class="form-control" name="queryBookName" placeholder="请输入要查询的书籍名称!" style="width: 280px"> <input type="submit" class="btn btn-primary" value="查询"> </form> </div> </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="${books}"> <tr> <td>${book.bookID}</td> <td>${book.bookName}</td> <td>${book.bookCounts}</td> <td>${book.detail}</td> <td> <a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改</a> | <a href="${pageContext.request.contextPath}/book/deleteBook?id=${book.bookID}">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>
addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>增加书籍</title> <!-- 新 Bootstrap 核心 CSS 文件 --> <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- jQuery文件。务必在bootstrap.min.js 之前引入 --> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> </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"> <%-- <div class="form-group">--%> <%-- <label for="bkid">书籍编号:</label>--%> <%-- <input type="text" name="bookID" class="form-control" id="bkid" required>--%> <%-- </div>--%> <div class="form-group"> <label for="bkname">书籍名称:</label> <input type="text" name="bookName" class="form-control" id="bkname" required> </div> <div class="form-group"> <label for="bkcounts">书籍数量:</label> <input type="text" name="bookCounts" class="form-control" id="bkcounts" required> </div> <div class="form-group"> <label for="bkdetail">书籍详情:</label> <input type="text" name="detail" class="form-control" id="bkdetail" required> </div> <div class="form-group"> <input type="submit" class="form-control" value="添加"> </div> </form> </div> </body> </html>
uodateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改书籍</title> <!-- 新 Bootstrap 核心 CSS 文件 --> <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- jQuery文件。务必在bootstrap.min.js 之前引入 --> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> </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"> <div class="form-group"> <label for="bkid">书籍编号:</label> <input type="text" name="bookID" class="form-control" id="bkid" value="${books.bookID}" readonly> </div> <%-- <input type="hidden" name="bookID" value="${books.bookID}">--%> <div class="form-group"> <label for="bkname">书籍名称:</label> <input type="text" name="bookName" class="form-control" id="bkname" value="${books.bookName}" required> </div> <div class="form-group"> <label for="bkcounts">书籍数量:</label> <input type="text" name="bookCounts" class="form-control" id="bkcounts" value="${books.bookCounts}" required> </div> <div class="form-group"> <label for="bkdetail">书籍详情:</label> <input type="text" name="detail" class="form-control" id="bkdetail" value="${books.detail}" required> </div> <div class="form-group"> <input type="submit" class="form-control" value="修改"> </div> </form> </div> </body> </html>