SSM整合

SSM整合

首先恭喜一下,总算路要到头了,即将迎接vue + SpringBoot

责任分工

测试

  • mysql:建库建表
/*不要一下全执行完*/
CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `songs`;

CREATE TABLE `songs` (
`songID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '歌id',
`songName` VARCHAR(100) NOT NULL COMMENT '歌名',
`songSellCounts` INT(11) NOT NULL COMMENT '销量',
`detail` VARCHAR(200) NOT NULL COMMENT '专辑',
KEY `songID` (`songID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `songs`(`songID`,`songName`,`songSellCounts`,`detail`)VALUES 
(1,'《红模仿》',1212,'《依然范特西》'),
(2,'《娘子》',13230,'《Jay》'),
(3,'《双截棍》',5,'《范特西》');
  • IDEA基本环境搭建

    • 新建项目,新建普通Maven项目即可
    • 导入依赖
    <!--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三兄弟 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
        <scope>provided</scope>
    </dependency>
    
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    
    <!--Mybatis-->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    
    <!--Spring-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.7</version>
    </dependency>
    
    • 静态资源导出
    <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>
    
    • 先立骨架

      • com.ice.pojo
      • com.ice.dao
      • com.ice.service
      • com.ice.controller
      • applicaitonContext.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>
      
      • 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>
      </configuration>
      
  • MyBatis

    • 数据库配置文件
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false
    jdbc.username=root
    jdbc.password=root
    
    • IDEA关联数据库(mysql8.0以上会有时区问题)
    • 编写实体类
    public class Songs {
        private int songID;
        private String songName;
        private int songSellCounts;
        private String detail;
    
        public Songs() {
        }
    
    
        public Songs(int songID, String songName, int songSellCounts, String detail) {
            this.songID = songID;
            this.songName = songName;
            this.songSellCounts = songSellCounts;
            this.detail = detail;
        }
    
        public int getSongID() {
            return songID;
        }
    
        public void setSongID(int songID) {
            this.songID = songID;
        }
    
        public String getSongName() {
            return songName;
        }
    
        public void setSongName(String songName) {
            this.songName = songName;
        }
    
        public int getSongSellCounts() {
            return songSellCounts;
        }
    
        public void setSongSellCounts(int songSellCounts) {
            this.songSellCounts = songSellCounts;
        }
    
        public String getDetail() {
            return detail;
        }
    
        public void setDetail(String detail) {
            this.detail = detail;
        }
    
        @Override
        public String toString() {
            return "Books{" +
                    "songID=" + songID +
                    ", songName='" + songName + '\'' +
                    ", songSellCounts=" + songSellCounts +
                    ", detail='" + detail + '\'' +
                    '}';
        }
    }
    
    • 编写核心配置文件
    <?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.ice.pojo"/>
        </typeAliases>
    </configuration>
    
    • 编写dao层

      • SongMapper
      public interface SongMapper {
          //增删查改,查{一首,全部}
      
          int addSong(Songs songs);
      
          int deleteSongById(int songID);
      
          Songs querySongById(int songID);
      
          List<Songs> queryAllSongs();
      
          int updateSong(Songs songs);
      }
      
      • SongMapper.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.ice.dao.SongMapper">
          <insert id="addSong" parameterType="songs">
              insert into songs
              (songID,songName,songSellCounts,detail)
              values (#{songID},#{songName},#{songSellCounts},#{detail})
          </insert>
      
          <delete id="deleteSongById">
              delete from songs
              where songID = #{songID}
          </delete>
      
          <select id="querySongById" resultType="songs">
              select * from songs
              where songID = #{songID}
          </select>
      
          <select id="queryAllSongs" resultType="songs">
              select * from songs
          </select>
      
          <update id="updateSongs" parameterType="songs">
              update songs
              set songName=#{songName},songSellCounts=#{songSellCounts},detail=#{detail}
              where songID=#{songID}
          </update>
      
      </mapper>
      
      • 记得将该mapper注册到核心配置文件中
    • 编写service层

      • SongService
      public interface SongService {
      
          int addSong(Songs songs);
      
          int deleteSongById(int songID);
      
          Songs querySongById(int songID);
      
          List<Songs> queryAllSongs();
      
          int updateSong(Songs songs);
      }
      
      
      • SongServiceImpl
      @Service  //注入容器
      public class SongServiceImpl implements SongService {
          @Autowired //自动装配
          //关联dao层
          private SongMapper songMapper;
      	//set注入
          public void setSongMapper(SongMapper songMapper) {
              this.songMapper = songMapper;
          }
      	//调用dao层方法
          public int addSong(Songs songs) {
              return songMapper.addSong(songs);
          }
      
          public int deleteSongById(int songID) {
              return songMapper.deleteSongById(songID);
          }
      
          public Songs querySongById(int songID) {
              return songMapper.querySongById(songID);
          }
      
          public List<Songs> queryAllSongs() {
              return songMapper.queryAllSongs();
          }
      
          public int updateSong(Songs songs) {
              return songMapper.updateSong(songs);
          }
      }
      

      MyBatis部分先告一段落,底子已经做好了!

  • Spring

    • spring-dao.xml(整合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">
        
        <!--1.关联数据库配置文件-->
        <context:property-placeholder location="classpath:datasource.properties"/>
        <!--2.连接池-->
        <!--常见连接池:dbcp,c3p0,druid-->
        <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.SqlSessionFactoryBean:现在交给Spring来做-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!--与mybatis-config.xml产生联系了-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
        <!--Dao接口自动注入到Spring容器-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!--扫描包下的所有接口-->
            <property name="basePackage" value="com.ice.dao"/>
        </bean>
    
    </beans>
    
    • spring-service.xml(整合service层)
    <?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.ice.service"/>
    
        <!--开启事务管理-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
        
        <!--可能还要用上AOP织入-->
    
    </beans>
    

    ok,Spring先暂告一段落!

  • 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">
        <!--1.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>
    
        <!--2.乱码问题-->
        <filter>
            <filter-name>encoding</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>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!--3.Session过期时间-->
        <session-config>
            <session-timeout>15</session-timeout>
        </session-config>
    </web-app>
    
    • 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
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
    	<!--1.注解驱动-->
        <mvc:annotation-driven/>
        <!--2.静态资源过滤-->
        <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>
    
        <!--为扫描到的包提供注解支持-->
        <context:component-scan base-package="com.ice.controller"/>
    
    </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="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>

</beans>
  • 前端与处理器

    • 查询功能

      • index.jsp
      <body>
          <h3><a href="${pageContext.request.contextPath}/song/allSongs">进入歌单页面</a></h3>
      </body>
      
      • SongController
      @Controller
      @RequestMapping("/song")
      public class SongController {
          @Autowired  //自动装配
          //关联service层
          private SongService songService;
      	//set注入
          public void setBookService(SongService songService) {
              this.songService = songService;
          }
      
          @RequestMapping("/allSongs")
          public String getAllBooks(Model model){
              //调用service层方法
              List<Songs> list = songService.queryAllSongs();
              model.addAttribute("list",list);
              return "allSongs";
          }
      }
      
      • allSongs.jsp
      <head>
          <title>歌单展示</title>
      
          <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
      </head>
      <body>
          <div class="container">
              <div class="row">
                  <div class="col-md-4 column">
                      <a class="btn btn-primary" href="${pageContext.request.contextPath}/song/toAddSong">新增歌曲</a>
                  </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>
                              </tr>
                          </thead>
                          <tbody>
                              <c:forEach var="song" items="${list}">
                                  <tr>
                                      <td>${song.songID}</td>
                                      <td>${song.songName}</td>
                                      <td>${song.songSellCounts}</td>
                                      <td>${song.detail}</td>
                                  </tr>
                              </c:forEach>
                          </tbody>
                      </table>
                  </div>
              </div>
          </div>
      </body>
      
    • 新增功能

      • 在allSongs.jsp新增a标签
      • SongController新增方法
      @RequestMapping("/toAddSong")
      public String toAddPage() {
          //视图跳转
          return "addSong";
      }
      
      • addSong.jsp
      <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}/song/addSong" method="post">
                  歌曲名称:<input type="text" name="songName" required><br><br><br>
                  销售数量:<input type="text" name="songSellCounts" required><br><br><br>
                  歌曲详情:<input type="text" name="detail" required><br><br><br>
                  <input type="submit" value="添加">
              </form>
          </div>
      </body>
      
      • SongController新增方法
      @RequestMapping("addSong")
      public String addSong(Songs songs){
          songService.addSong(songs);
          //使用重定向!
          return "redirect:/song/allSongs";
      }
      

      假如使用请求转发,会出现表单重复提交的情况。

  • 修改和删除功能

    • allSongs.jsp

      <body>
      <div class="container">
          <div class="row">
              <div class="col-md-4 column">
                  <a class="btn btn-primary" href="${pageContext.request.contextPath}/song/toAddSong">新增歌曲</a>
              </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="song" items="${list}">
                              <tr>
                                  <td>${song.songID}</td>
                                  <td>${song.songName}</td>
                                  <td>${song.songSellCounts}</td>
                                  <td>${song.detail}</td>
                                  <!--此处丢链接,界面美观功能明确-->
                                  <td><a href="${pageContext.request.contextPath}/song/toUpdatePage?songID=${song.songID}">修改</a>&nbsp;|&nbsp;<a href="${pageContext.request.contextPath}/song/deleteSong/${song.songID}">删除</a></td>
                              </tr>
                          </c:forEach>
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
      
      </body>
      
      • SongController
      @RequestMapping("/toUpdatePage")
      public String toUpdatePage(int songID,Model model){
          Songs songs = songService.querySongById(songID);
          model.addAttribute("songs",songs);
          return "updateSong";
      }
      
      @RequestMapping("/updateSong")
      public String updateSong(Songs songs){
          songService.updateSong(songs);
          return "redirect:/song/allSongs";
      }
      
      @RequestMapping("/deleteSong/{songID}")
      public String deleteSong(@PathVariable("songID") int songID){
          songService.deleteSongById(songID);
          return "redirect:/song/allSongs";
      
      }
      
      • updateSong.jsp

      复用新增页面

      <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}/song/updateSong" method="post">
              <!--小技巧:隐藏域-->
              <input type="hidden" name="songID" value="${songs.songID}">
              歌曲名称:<input type="text" name="songName" required value="${songs.songName}"><br><br><br>
              销售数量:<input type="text" name="songSellCounts" required value="${songs.songSellCounts}"><br><br><br>
              歌曲详情:<input type="text" name="detail" required value="${songs.detail}"><br><br><br>
              <input type="submit" value="修改">
          </form>
      
      </div>
      </body>
      </body>
      
posted @ 2021-06-08 22:34  Code_Ice  阅读(50)  评论(0)    收藏  举报