SSM框架整合

要求:
需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识

数据库

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

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,'从进门到进牢');

基本环境搭建

1、新建一Maven项目, 添加web的支持

2、导入相关的pom依赖!

<dependencies>
   
   <dependency>
       <groupId>junitgroupId>
       <artifactId>junitartifactId>
       <version>4.12version>
   dependency>
   
   <dependency>
       <groupId>mysqlgroupId>
       <artifactId>mysql-connector-javaartifactId>
       <version>5.1.47version>
   dependency>
   
   <dependency>
       <groupId>com.mchangegroupId>
       <artifactId>c3p0artifactId>
       <version>0.9.5.2version>
   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.2version>
   dependency>
   <dependency>
       <groupId>org.mybatisgroupId>
       <artifactId>mybatis-springartifactId>
       <version>2.0.2version>
   dependency>

   
   <dependency>
       <groupId>org.springframeworkgroupId>
       <artifactId>spring-webmvcartifactId>
       <version>5.1.9.RELEASEversion>
   dependency>
   <dependency>
       <groupId>org.springframeworkgroupId>
       <artifactId>spring-jdbcartifactId>
       <version>5.1.9.RELEASEversion>
   dependency>
dependencies>

3、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>

4、建立基本结构和配置框架!

  • com.Devin.pojo

  • com.Devin.dao

  • com.Devin.service

  • com.Devin.controller

  • mybatis-config.xml



<configuration>

configuration>
  • applicationContext.xml

<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层

1、数据库配置文件 database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

2、IDEA关联数据库

3、编写MyBatis的核心配置文件 mybatis-config.xml



<configuration>
    
    
    <typeAliases>
        <package name="com.Devin.pojo"/>
    typeAliases>

    
    <mappers>
        <mapper class="com.Devin.dao.BookMapper"/>
    mappers>
configuration>

4、编写数据库对应的实体类 com.Devin.pojo.Books

使用lombok插件!

package com.Devin.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor//有参
@NoArgsConstructor//无参
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

5、编写Dao层的 Mapper接口!BookMapper

package com.Devin.dao;

import com.Devin.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;
/*
数据层
 */
public interface BookMapper {
    //增加一个Book
    int addBook(Books book);

    //根据id删除一个Book
    int deleteBookById(@Param("bookId") int id);

    //更新Book
    int updateBook(Books books);

    //根据id查询,返回一个Book
    Books queryBookById(@Param("bookId") int id);

    //查询全部Book,返回list集合
    List<Books> queryAllBook();

    /*
    前端页面查询书籍
     */
    Books queryBookByName(@Param("bookName") String bookName);
}

6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;

<?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.Devin.dao.BookMapper">
    <!--增加一本书
    parameterType:参数类型
    -->
    <!--增加一个Book-->
    <insert id="addBook" parameterType="Books">
      insert into ssmbuild.books(bookName,bookCounts,detail)
      values (#{bookName}, #{bookCounts}, #{detail})
   </insert>

    <!--根据id删除一个Book-->
    <delete id="deleteBookById" parameterType="int">
      delete from ssmbuild.books where bookID=#{bookID}
   </delete>

    <!--更新Book-->
    <update id="updateBook" parameterType="Books">
      update ssmbuild.books
      set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
      where bookID = #{bookID}
   </update>

    <!--根据id查询,返回一个Book-->
    <select id="queryBookById" resultType="Books">
      select * from ssmbuild.books
      where bookID = #{bookID}
   </select>

    <!--查询全部Book-->
    <select id="queryAllBook" resultType="Books">
      SELECT * from ssmbuild.books
   </select>

    <!--前端页面查询书籍-->
    <select id="queryBookByName" resultType="Books">
        select * from ssmbuild.books where bookName = #{bookName}
    </select>
</mapper>

7、编写Service层的接口(BookService)和实现类(BookServiceImpl)

接口:

package com.Devin.service;

import com.Devin.pojo.Books;

import java.util.List;
/*
业务层
service和dao层一样,都是Model层
 */
public interface BookService {
    //增加一个Book
    int addBook(Books book);
    //根据id删除一个Book
    int deleteBookById(int id);
    //更新Book
    int updateBook(Books books);
    //根据id查询,返回一个Book
    Books queryBookById(int id);
    //查询全部Book,返回list集合
    List<Books> queryAllBook();

    /*
    前端页面查询书籍
     */
    Books queryBookByName(String bookName);
}

实现类:

package com.Devin.service;

import com.Devin.dao.BookMapper;
import com.Devin.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService {

    //调用dao层的操作,设置一个set接口,方便Spring管理
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public int addBook(Books book) {
        return bookMapper.addBook(book);
    }

    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

    public Books queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }
}

整合Spring框架

1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;

2、编写Spring整合Mybatis的相关的配置文件;spring-dao.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"
       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="com.Devin.dao"/>
    bean>

beans>

3、Spring整合service层


<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
   http://www.springframework.org/schema/context/spring-context.xsd">
    
    
    <context:component-scan base-package="com.Devin.service" />

    
    <bean id="BookServiceImpl" class="com.Devin.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource" />
    bean>

beans>

整合SpringMVC层

1、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.CharacterEncodingFilter
       filter-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>

2、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
   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="com.Devin.controller" />

beans>

3、Spring配置整合文件,applicationContext.xml


<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>


ssm框架结构基本整合完毕了,下面我们就写一些具体的案例!!

Controller 和 视图层编写

方法一:查询全部书籍

1、BookController 类编写

@Controller
@RequestMapping("/book")
public class BookController {
    //controller 调用service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    /*
    方法一:查询全部的书籍
    查询全部的书籍,并且返回到一个书籍展示页面
     */
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();
        //返回给前端页面展示
        model.addAttribute("list", list);

        return "allBook";
  }
}

2、编写视图层(.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
    <style>
      a {
        /*去掉下划线*/
        text-decoration: none;
        /*字体颜色*/
        color: blueviolet;
        /*字体大小*/
        font-size: 18px;

      }

      h3{
        width: 180px;
        height: 38px;
        /*左右剧中*/
        margin: 100px auto;
        text-align: center;
        /*上下居中:和高度一样就可以了*/
        line-height: 38px;
        /*背景颜色*/
        background: deepskyblue;
        /*圆角边框*/
        border-radius: 5px;

      }

    </style>
  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
  </h3>
  </body>
</html>

3、书籍列表页面 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">
    <!-- 引入 Bootstrap -->
    <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">
            <%--新增书籍--%>
            <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 class="from-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
                <span style="color: red; font-weight:bold">${error}</span>
                <input type="text" name="queryBookName" class="from-control" 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/toUpdate?id=${book.getBookID()}">修改</a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>


</body>
</html>

方法二:添加书籍

1、BookController 类编写

//跳转到添加书籍页面
    @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";//重定向到我们的@RaequestMapper("/allBook")请求;
    }

2、编写视图层(andBook.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">
    <!-- 引入 Bootstrap -->
    <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">
        <div class="form-group">
            <label>书籍名称:</label>
            <input type="text" name="bookName" class="form-control" required>
        </div>
        <div class="form-group">
            <label>书籍数量:</label>
            <input type="text" name="bookCounts" class="form-control" required>
        </div>
        <div class="form-group">
            <label>书籍数量:</label>
            <input type="text" name="bookCounts" class="form-control" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="修改">
        </div>
    </form>

</div>

方法三:修改书籍

1、BookController 类编写

@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";
}

2、编写视图层(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">
   <!-- 引入 Bootstrap -->
   <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>

方法四:删除书籍

1、BookController 类编写

@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable(“bookId”) int id) {
bookService.deleteBookById(id);
return “redirect:/book/allBook”;
}

配置Tomcat


项目结构图

SSM框架整合_第1张图片
SSM框架整合_第2张图片


本文章来源于B站(狂神说) B站地址:https://space.bilibili.com/95256449

你可能感兴趣的:(springmvc,Spring)