整合SSM框架 -- 简单基础SSM项目

整合SSM框架 – 第一个SSM项目

学完MyBatis、Spring、SpringMVC,做一个基于SSM框架的基础项目–书籍管理系统,要求可以实现数据的增删改查,业务运行逻辑明了,分层开发,用来巩固学习

目标:

  • 配置SSM框架
  • 实现基础的增删改查功能
  • 具备后续方便的拓展功能
  • 界面设计整洁

最终效果:

  • 全部书籍页面

    整合SSM框架 -- 简单基础SSM项目_第1张图片

  • 新增书籍页面

    整合SSM框架 -- 简单基础SSM项目_第2张图片

  • 查询书籍页面

    整合SSM框架 -- 简单基础SSM项目_第3张图片


环境:

开发环境

环境:

  • IDEA 2021.2.1
  • MySQL 8
  • Tomcat 9
  • Maven 3.8

数据库环境

创建一个存放书籍数据的数据库表

数据库ssmbuild 书籍信息表books 主键bookID自动增长 所有字段都不能为空

CREATE
    DATABASE `ssmbuild`;

USE
    `ssmbuild`;

-- 创建图书表
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', 34, '从入门到放弃'),
       (2, 'MySQL', 23, '从删库到跑路'),
       (3, 'Linux', 33, '从进门到进牢')

基本环境搭建

项目结构

整合SSM框架 -- 简单基础SSM项目_第4张图片

整合SSM框架 -- 简单基础SSM项目_第5张图片

项目搭建

  1. 新建一个Maven项目 ssmbuild , 添加JavaWeb框架的支持

  2. 在pom文件中导入所需依赖

    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.26version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.5version>
        dependency>
    
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
    
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>
    
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.11version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.11version>
        dependency>
    
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.7version>
        dependency>
    
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.22version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
    dependencies>
    

    整合SSM框架 -- 简单基础SSM项目_第6张图片

  3. 配置项目依赖

    整合SSM框架 -- 简单基础SSM项目_第7张图片

    整合SSM框架 -- 简单基础SSM项目_第8张图片

  4. Maven资源过滤设置

    
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>
    
  5. 建立基本结构和配置框架

    整合SSM框架 -- 简单基础SSM项目_第9张图片

  6. 编写java代码

    • 编写数据库对应的实体类 pojo.Books.java (注:这里使用了Lombok插件)

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class Books {
      
          private int bookID;
          private String bookName;
          private int bookCounts;
          private String detail;
      
      }
      
    • 编写Mapper接口 mapper/BookMapper.java

      public interface BookMapper {
      
          // 增加
          int insertBook(Books books);
      
          // 删除
          int deleteBook(@Param("bookId") int id);
      
          // 修改
          int updateBook(Books books);
      
          // ID查询
          Books queryBookById(int id);
      
          // 查询全部
          List<Books> queryAllBook();
      
          // 模糊查询
          List<Books> queryBookName(@Param("bookName") String bookName);
      
      }
      
    • 编写Mapper接口对应的XML文件

      
      DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.codeonce.mapper.BookMapper">
      
          
          <insert id="insertBook" parameterType="Books">
              INSERT INTO ssmbuild.books(bookName, bookCounts, detail)
              VALUES (#{bookName}, #{bookCounts}, #{detail});
          insert>
      
          
          <delete id="deleteBook" parameterType="int">
              DELETE
              FROM ssmbuild.books
              WHERE bookID = #{bookId};
          delete>
      
          
          <update id="updateBook" parameterType="Books">
              UPDATE ssmbuild.books
              SET bookName=#{bookName},
                  bookCounts=#{bookCounts},
                  detail=#{detail}
              WHERE bookID = #{bookID};
          update>
      
          
          <select id="queryBookById" resultType="Books">
              SELECT *
              FROM ssmbuild.books
              WHERE bookID = #{bookId};
          select>
      
          
          <select id="queryAllBook" resultType="Books">
              SELECT *
              FROM ssmbuild.books;
          select>
      
          
          <select id="queryBookName" resultType="Books">
              SELECT *
              FROM ssmbuild.books
              WHERE bookName LIKE CONCAT('%', #{bookName}, '%');
          select>
      mapper>
      
    • 编写Service层接口 service/BookService.java

      public interface BookService {
      
          // 增加
          int insertBook(Books books);
      
          // 删除
          int deleteBook(@Param("bookId") int id);
      
          // 修改
          int updateBook(Books books);
      
          // ID查询
          Books queryBookById(int id);
      
          // 查询全部
          List<Books> queryAllBook();
      
          // 查询全部
          List<Books> queryBookName(String bookName);
      }
      
    • 编写Service层接口实现类 service/BookServiceImpl.java

      public class BookServiceImpl implements BookService {
          // 配置LOG4J
          private static final Logger logger = Logger.getLogger(BookServiceImpl.class);
      
          // service调用mapper层
          private BookMapper bookMapper;
      
          public void setBookMapper(BookMapper bookMapper) {
              this.bookMapper = bookMapper;
          }
      
          @Override
          public int insertBook(Books books) {
              return bookMapper.insertBook(books);
          }
      
          @Override
          public int deleteBook(int id) {
              return bookMapper.deleteBook(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> queryAllBook() {
              return bookMapper.queryAllBook();
          }
      
          @Override
          public List<Books> queryBookName(String bookName) {
              return bookMapper.queryBookName(bookName);
          }
      }
      
    • 编写控制层 controller/BookController.java

      import com.codeonce.pojo.Books;
      import com.codeonce.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.List;
      
      @Controller
      @RequestMapping("/book")
      public class BookController {
      
          // controller 调用 service层
          @Autowired
          @Qualifier("BookServiceImpl")
          private BookService bookService;
      
          // 查询全部的书籍,并且返回到一书籍展示的页面
          @RequestMapping("/allBook")
          public String queryAll(Model model) {
              List<Books> booksList = bookService.queryAllBook();
              model.addAttribute("booksList", booksList);
              return "allBook";
          }
      
          // 跳转到增加书籍页面
          @RequestMapping("/toAddBook")
          public String toAddBookPaper() {
              return "addBook";
          }
      
          // 添加书籍的请求
          @RequestMapping("/addBook")
          public String insertBook(Books books) {
              System.out.println("addBook=>" + books);
              int result = bookService.insertBook(books);
              if (result > 0) {
                  System.out.println("添加数据成功" + books);
              }
              return "redirect:/book/allBook";
          }
      
          // 跳转到修改书籍页面
          @RequestMapping("/toUpdateBook/{bookID}")
          public String toUpdateBookPaper(@PathVariable("bookID") int id, Model model) {
              Books books = bookService.queryBookById(id);
              model.addAttribute("books", books);
              return "updateBook";
          }
      
          // 修改书籍请求
          @RequestMapping("/updateBook")
          public String updateBook(Books books) {
              System.out.println("updateBook=>" + books);
              int result = bookService.updateBook(books);
              if (result > 0) {
                  System.out.println("修改数据成功" + books);
              }
              return "redirect:/book/allBook";
          }
      
          // 删除书籍请求
          @RequestMapping("/deleteBook/{bookID}")
          public String deleteBook(@PathVariable("bookID") int id) {
              int result = bookService.deleteBook(id);
              if (result > 0) {
                  System.out.println("删除数据成功" + id);
              }
              return "redirect:/book/allBook";
          }
      
          // 查询书籍
          @RequestMapping("/queryBook")
          public String queryBook(String bookName, Model model) {
              // bookName = "%" + bookName + "%";
              List<Books> booksList = bookService.queryBookName(bookName);
              System.err.println("queryBook" + booksList);
              model.addAttribute("booksList", booksList);
              return "allBook";
          }
      
      }
      
  7. 配置文件

    • 数据库参数配置文件 resources/database.properties

      jdbc.driver=com.mysql.cj.jdbc.Driver
      jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
      jdbc.username=root
      jdbc.password=admin
      
    • LOG4J日志配置文件 resources/log4j.properties

      # 将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
      log4j.rootLogger=DEBUG,console,file
      # 控制台输出的相关设置
      log4j.appender.console=org.apache.log4j.ConsoleAppender
      log4j.appender.console.Target=System.out
      log4j.appender.console.Threshold=DEBUG
      log4j.appender.console.layout=org.apache.log4j.PatternLayout
      log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
      log4j.appender.Console.encoding=UTF-8
      # 文件输出的相关设置
      log4j.appender.file=org.apache.log4j.RollingFileAppender
      log4j.appender.file.File=./log/com.mydemo.log
      log4j.appender.file.MaxFileSize=10mb
      log4j.appender.file.Threshold=DEBUG
      log4j.appender.file.layout=org.apache.log4j.PatternLayout
      log4j.appender.file.layout.ConversionPattern=[%p][%d{yyyy-MM-dd}][%c]%m%n
      log4j.appender.file.encoding=UTF-8
      # 日志输出级别
      log4j.logger.org.mybatis=DEBUG
      log4j.logger.java.sql=DEBUG
      log4j.logger.java.sql.Statement=DEBUG
      log4j.logger.java.sql.ResultSet=DEBUG
      log4j.logger.java.sql.PreparedStatement=DEBUG
      
    • 写dao层操作配置文件 resources/spring-dao.xml

      
      <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                  https://www.springframework.org/schema/beans/spring-beans.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-4.0.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="com.codeonce.mapper"/>
          bean>
      
      beans>
      
    • 写service层操作配置文件 resources/spring-service.xml

      
      <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
                 http://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">
      
          
          <context:component-scan base-package="com.codeonce.service"/>
      
          
          <bean id="BookServiceImpl" class="com.codeonce.service.BookServiceImpl">
              <property name="bookMapper" ref="bookMapper"/>
          bean>
      
          
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              
              <property name="dataSource" ref="dataSource"/>
          bean>
      
          
          
          
          <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.codeonce.mapper.*.*(..))"/>
              
              <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
          aop:config>
      
      beans>
      
    • 写MVC操作配置文件 resources/spring-mvc.xml

      
      <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">
      
          
          <mvc:annotation-driven/>
      
          
          <mvc:default-servlet-handler/>
      
          
          <context:component-scan base-package="com.codeonce.controller"/>
      
          
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
              
              <property name="prefix" value="/WEB-INF/jsp/"/>
              
              <property name="suffix" value=".jsp"/>
          bean>
      
      beans>
      
    • mybatis框架配置 resources/mybatis-config.xml

      
      DOCTYPE configuration PUBLIC "-//mybatis.ory//DTD Config 3.0//EN" "htpp://mybatis.org/dtd/mybatis-3-config.dtd">
      
      <configuration>
      
          
          <settings>
              
              <setting name="logImpl" value="STDOUT_LOGGING"/>
              
          settings>
      
          
          <typeAliases>
              <typeAlias type="com.codeonce.pojo.Books" alias="Books"/>
          typeAliases>
      
          <mappers>
              <mapper class="com.codeonce.mapper.BookMapper"/>
          mappers>
      
      configuration>
      
    • 导入所有配置文件 resources/applicationContext.xml

      
      <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                  https://www.springframework.org/schema/beans/spring-beans.xsd
                  http://www.springframework.org/schema/context
                  https://www.springframework.org/schema/context/spring-context.xsd">
      
          
          <context:annotation-config/>
      
          <import resource="classpath:spring-dao.xml"/>
          <import resource="classpath:spring-service.xml"/>
          <import resource="classpath:spring-mvc.xml"/>
      
      beans>
      
    • 在web.xml 中绑定配置 web/WEB-INF/web.xml

      
      <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>DispatcherServletservlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
              
              <init-param>
                  <param-name>contextConfigLocationparam-name>
                  <param-value>classpath:applicationContext.xmlparam-value>
              init-param>
              
              <load-on-startup>1load-on-startup>
          servlet>
      
          
          <servlet-mapping>
              <servlet-name>DispatcherServletservlet-name>
              <url-pattern>/url-pattern>
          servlet-mapping>
      
          
          <filter>
              <filter-name>encodingFilterfilter-name>
              <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
              <init-param>
                  <param-name>encodingparam-name>
                  <param-value>utf-8param-value>
              init-param>
          filter>
          <filter-mapping>
              <filter-name>encodingFilterfilter-name>
              <url-pattern>/*url-pattern>
          filter-mapping>
      
          
          <session-config>
              <session-timeout>15session-timeout>
          session-config>
      
      web-app>
      
  8. JSP页面

    • 整合SSM框架 -- 简单基础SSM项目_第10张图片

    • index.jsp 跳转页面 web/index.jsp

      <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
      
      
      
          跳转页面
          
      
      
      
      

      点击进入列表页

    • 书籍列表JSP web/WEB-INF/jsp/allBook.jsp (集成查询所有和模糊查询)

      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      
      
      
          
          
          
          书籍列表
          
          
      
      
      
      
      
      
      <%--新增--%>
      <%--查询--%>
      <%-- 未查询到任何结果--%>
      书籍编号 书籍名字 书籍数量 书籍详情 操作
      ${book.bookID} ${book.bookName} ${book.bookCounts} ${book.detail} 更改 | 删除
    • 新增书籍页面 web/WEB-INF/jsp/addBook.jsp

      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      
      
      
          新增书籍
          
          
          
      
      
      
    • 更新书籍JSP页面 web/WEB-INF/jsp/updateBook.jsp (此处可以使用新增书籍页面复用)

      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      
      
      
          修改书籍
          
          
          
      
      
      

      总结

      1. 代码还有很多地方可以改进 比如页面代码复用 方法复用 动态SQL
      2. 后续进行项目拓展都可以基于需求进行增加mapper接口

你可能感兴趣的:(Java基础笔记,java,ssm,spring)