自学SSM之整合SSM框架

整合ssm框架

  1. 新建一个项目,确保导入依赖

    <?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.ryan</groupId>
        <artifactId>ssmbuild</artifactId>
        <version>1.0-SNAPSHOT</version>
        <!--依赖:junit mysql数据库 数据库连接池 jsp mybatis spring lombok-->
        <dependencies>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
            </dependency>
    
            <!--数据库-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
    
            <!--数据库连接池,这里尝试使用c3p0-->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>
    
            <!--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.4</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.4</version>
            </dependency>
    
            <!-- 日志 -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
            <!--spring-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.5.RELEASE</version>
            </dependency>
    
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
            </dependency>
        </dependencies>
    
        <!--静态资源导出问题-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
            </resources>
        </build>
    
        <!--jdk版本问题-->
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <!--修改Language level-->
            <maven.compiler.source>11</maven.compiler.source>
            <!--修改Java Compiler-->
            <maven.compiler.target>11</maven.compiler.target>
        </properties>
    </project>
    
  2. 新建必要的包:pojo、dao、service、controller

  3. 提供配置文件

    • 两大核心配置文件: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">
      <!--mybatis的主配置文件-->
      <configuration>
          <settings>
              <setting name="logImpl" value="LOG4J"/>
          </settings>
          <typeAliases>
              <package name="com.ryan.pojo"/>
          </typeAliases>
          <mappers>
              <mapper class="com.ryan.dao.BookMapper"/>
          </mappers>
      </configuration>
      
  4. 完善mybatis层

    • 提供数据库文件database.properties和日志文件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.file = org.apache.log4j.RollingFileAppender
      log4j.appender.file.File=./log/ryan.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{yy-MM-dd}][%c]%m%n
      
      #日志输出级别
      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
      
      jdbc.driver=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8
      jdbc.username=root
      jdbc.password=1227
      
    • 编写pojo包下的实体类

    • 编写dao包下的接口和对应的mapper

    • 编写mybatis核心配置文件(注册mapper)

    • 编写servece包下的接口和实现类

  5. 完善spring层

    • 整合spring-dao:连接数据库和连接池,获取sqlSessionFactory,自动注入

      <?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:aop="http://www.springframework.org/schema/aop"
             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/aop
              https://www.springframework.org/schema/aop/spring-aop.xsd
              http://www.springframework.org/schema/context
              https://www.springframework.org/schema/context/spring-context.xsd">
      
          <!--1.获取数据库配置文件-->
          <context:property-placeholder location="classpath:database.properties"/>
          <!--2.连接池,这里使用c3p0,以后还会接触druid,之前使用的是spring自带的-->
          <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"/>
              <!--关闭连接后补自动commit-->
              <property name="autoCommitOnClose" value="false"/>
              <!--获取连接超时时间-->
              <property name="checkoutTimeout" value="10000"/>
              <!--当获取连接失败重试次数-->
              <property name="acquireRetryAttempts" value="2"/>
          </bean>
      
          <!--3.获取sqlSessionFactory-->
          <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource"/>
              <!--绑定Mybatis核心配置文件-->
              <property name="configLocation" value="classpath:mybatis-config.xml"/>
          </bean>
      
          <!--4.配置dao接口扫描包,动态的实现了DAO接口可以注入到spring容器中-->
          <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <!--注入sqlSessionFactory-->
              <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
              <!--要扫描的dao包-->
              <property name="basePackage" value="com.ryan.dao"/>
          </bean>
      </beans>
      
    • 整合spring-service:扫描service包,业务注入,声明式事务配置、aop织入(需要的话)

      <?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:aop="http://www.springframework.org/schema/aop"
             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/aop
              https://www.springframework.org/schema/aop/spring-aop.xsd
              http://www.springframework.org/schema/context
              https://www.springframework.org/schema/context/spring-context.xsd">
      
          <!--1.扫描service包-->
          <context:component-scan base-package="com.ryan.service"/>
          <!--2.将service层的业务都注入到spring中,可用xml配置,也可以使用注解,这里配置一下-->
          <bean id="BookServiceImpl" class="com.ryan.service.BookServiceImpl">
              <property name="bookMapper" ref="bookMapper"/>
          </bean>
          <!--3.声明式事务-->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource"/>
          </bean>
          <!--4.如果有需要的话,还可以添加aop织入,这里就不加了-->
      
      </beans>
      
  6. 完善springmvc层

    • 增加web项目支持,确保lib目录导入

    • 编写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">
      
          <!--Dispatcher-->
          <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>
      
          <!--sqlSession-->
          <session-config>
              <session-timeout>15</session-timeout>
          </session-config>
      </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:aop="http://www.springframework.org/schema/aop"
             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/aop
              https://www.springframework.org/schema/aop/spring-aop.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.ryan.controller"/>
          <!--注解驱动-->
          <mvc:annotation-driven/>
          <!--过滤静态资源-->
          <mvc:default-servlet-handler/>
          <!--视图解析器-->
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/jsp/"/>
              <property name="suffix" value=".jsp"/>
          </bean>
      </beans>
      
  7. 整合所有spring配置文件: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: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/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <import resource="spring-dao.xml"/>
        <import resource="spring-service.xml"/>
        <import resource="spring-mvc.xml"/>
    
    </beans>
    
  8. 编写controller层

    package com.ryan.controller;
    
    import com.ryan.pojo.Books;
    import com.ryan.service.BookService;
    import org.apache.ibatis.annotations.Param;
    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("/allBooks")
        public String list(Model model){
            List<Books> list = bookService.queryAllBooks();
            model.addAttribute("list",list);
            return "allBooks";
        }
    
        //跳转到增加书籍页面
        @RequestMapping("/toAddBook")
        public String toAddPaper(){
            return "addBook";
        }
    
        //增加书籍后回到书籍列表
        @RequestMapping("/addBook")
        public String addBook(Books book){
            bookService.addBook(book);
            return "redirect:/book/allBooks";
        }
    
        //删除书籍
        @RequestMapping("/deleteBook/{bookID}")
        public String deleteBook(@PathVariable("bookID") int id){
            bookService.deleteBook(id);
            return "redirect:/book/allBooks";
        }
    
        //跳转到修改书籍页面
        @RequestMapping("/toUpdateBook/{bookID}")
        public String toUpdatePaper(@PathVariable("bookID")int id,  Model model){
            Books books = bookService.queryBookById(id);
            model.addAttribute("books",books);
            return "updateBook";
        }
    
        //修改书籍页面
        @RequestMapping("/updateBook")
        public String updateBook(Books book){
            bookService.updateBook(book);
            return "redirect:/book/allBooks";
        }
    }
    
  9. 结合第8步编写前端页面

    • 书籍列表(查询全部书籍)
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>图书管理系统</title>
        <script src="${pageContext.request.contextPath}/js/jquery3.5.0.js"></script>
        <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12">
                <div class="page-header">
                    <h1>
                        <small>书籍列表——————显示所有书籍</small>
                    </h1>
                </div>
            </div>
        </div>
    
        <div class="row">
            <div class="col-md-4">
                <a class="btn btn-default" role="button" href="${pageContext.request.contextPath}/book/toAddBook">添加书籍</a>
            </div>
            <div style="float: right">
                <form class="form-inline">
                    <div class="form-group">
                        <input type="text" class="form-control" id="queryBookName" name="bookName" placeholder="书籍名称">
                    </div>
                    <button type="submit" class="btn btn-default">查询</button>
                </form>
            </div>
    
        </div>
    
        <div class="row clearfix">
            <div class="col-md-12">
                <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="${list}">
                            <tr>
                                <td>${book.bookID}</td>
                                <td>${book.bookName}</td>
                                <td>${book.bookCounts}</td>
                                <td>${book.detail}</td>
                                <td><a href="${pageContext.request.contextPath}/book/toUpdateBook/${book.bookID}">修改</a> | <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a> </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </body>
    </html>
    
    
    • 添加书籍
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>图书管理系统-新增书籍</title>
        <script src="${pageContext.request.contextPath}/js/jquery3.5.0.js"></script>
        <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 colum">
                <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="bkname">书籍名称</label>
                <input type="text" name="bookName" class="form-control" id="bkname">
            </div>
            <div class="form-group">
                <label for="bkcounts">书籍库存</label>
                <input type="text" name="bookCounts" class="form-control" id="bkcounts">
            </div>
            <div class="form-group">
                <label for="detail">书籍描述</label>
                <input type="text" name="detail" class="form-control" id="detail">
            </div>
            <button type="submit" class="btn btn-default">添加</button>
        </form>
    </div>
    </body>
    </html>
    
    • 修改书籍
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>图书管理系统-修改书籍</title>
        <script src="${pageContext.request.contextPath}/js/jquery3.5.0.js"></script>
        <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 colum">
                <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="${books.bookID}">
            <div class="form-group">
                <label for="bkname">书籍名称</label>
                <input type="text" name="bookName" value="${books.bookName}" class="form-control" id="bkname">
            </div>
            <div class="form-group">
                <label for="bkcounts">书籍库存</label>
                <input type="text" name="bookCounts" value="${books.bookCounts}" class="form-control" id="bkcounts">
            </div>
            <div class="form-group">
                <label for="detail">书籍描述</label>
                <input type="text" name="detail" value="${books.detail}" class="form-control" id="detail">
            </div>
            <button type="submit" class="btn btn-default">修改</button>
        </form>
    </div>
    </body>
    </html>
    

总结:

  • 配置太多,不用特意去死记硬背,可以一边做项目一边加强记忆
  • controller层和前端的逻辑一定要清晰
  • 前端提交表单的,要考虑到以下几点
    • 属性:action、method、name
    • 是否需要传参
  • 前端的一些样式还是要稍微去学习以下

展望:ssm框架的重要程度是不言而喻的,学到这里,大家已经可以进行基本网站的单独开发,但是这只是增删改查的基本操作,可以说学到这里,大家才算是真正的步入了后台开发的门,也就是能找一个后台相关工作的底线。

或许很多人,工作就是做这些事情,但是对于个人的提高来说,这远远不够!

学习来源:B站up主,狂神说

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值