SSM框架整合部分来啦!!!

SSM框架整合

1.导入maven依赖

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</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.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</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.1-b03</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

2.数据库环境搭建

CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE
IF
	EXISTS `books`;
CREATE TABLE `book` (
	`id` INT auto_increment PRIMARY KEY,
	`bookId` INT NOT NULL DEFAULT 0 COMMENT '书号',
	`bookName` VARCHAR ( 100 ) NOT NULL COMMENT '书名',
	`bookCount` INT NOT NULL DEFAULT 0 COMMENT '数量',
	`description` VARCHAR ( 200 ) COMMENT '描述',
	KEY `bookId` ( `bookId` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8 
USE `book`;
INSERT INTO `book`
VALUES
	( 1, 1, 'Java', 1, 'Java是世界上最好的语言' ),
	( 2, 2, 'Mysql', 1, 'mysql也不难' ),
	( 3, 3, 'Linux', 1, 'Linux也要学' );

3.mybatis层

3.1.编写连接数据库配置

#database.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=Chenzuwei_0817

3.2.创建实体类

package com.alinu.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author Chenzuwei
 * @description
 * @createTime 2020-08-22 12:46
 * @since 1.0.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private int id;
    private int bookId;
    private String bookName;
    private int bookCount;
    private String description;
}

3.3.编写数据库接口

package com.alinu.dao;

import com.alinu.pojo.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author Chenzuwei
 * @description
 * @createTime 2020-08-22 12:49
 * @since 1.0.0
 */
public interface BookMapper {
    int addBook(Book book);

    int deleteBook(@Param("bookId") int bookId);

    List<Book> searchAll();

    Book searchById(@Param("bookId") int bookId);

    int updateBook(Book book);

}

3.4.创建xml编写SQL操作

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.alinu.dao.BookMapper">
    <insert id="addBook" parameterType="Book">
        insert into book(bookId, bookName, bookCount, description)
        values (#{bookId}, #{bookName}, #{bookCount}, #{description});
    </insert>

    <delete id="deleteBook" parameterType="int">
        delete from book where bookId = #{bookId};
    </delete>

    <select id="searchById" resultType="Book">
        select * from book where bookId = #{bookId};
    </select>

    <select id="searchAll" resultType="Book">
        select * from book;
    </select>

    <update id="updateBook" parameterType="Book">
        update book
        set bookId=#{bookId}, bookName=#{bookName}, bookCount=#{bookCount}, description=#{description}
        where bookId=#{bookId};
    </update>

</mapper>

3.5.创建mybatis配置文件

<?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="" value=""/>-->
<!--    </settings>-->
    <typeAliases>
        <typeAlias type="com.alinu.pojo.Book" alias="Book"/>
    </typeAliases>
    <mappers>
        <mapper resource="BookMapper.xml"/>
    </mappers>
</configuration>

4.Spring层

4.1.创建业务层

package com.alinu.service;

import com.alinu.pojo.Book;

import java.util.List;

/**
 * @author Chenzuwei
 * @description
 * @createTime 2020-08-22 13:49
 * @since 1.0.0
 */
public interface BookService {
    int addBook(Book book);

    int deleteBook(int bookId);

    List<Book> searchAll();

    Book searchById(int bookId);

    int updateBook(Book book);
}

package com.alinu.service;

import com.alinu.dao.BookMapper;
import com.alinu.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Chenzuwei
 * @description
 * @createTime 2020-08-22 13:50
 * @since 1.0.0
 */
public class BookServiceImpl implements BookService{

    private BookMapper bookMapper;

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

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

    public int deleteBook(int bookId) {
        return bookMapper.deleteBook(bookId);
    }

    public List<Book> searchAll() {
        return bookMapper.searchAll();
    }

    public Book searchById(int bookId) {
        return bookMapper.searchById(bookId);
    }

    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }
}

4.2.spring整合dao和service

  • spring-dao.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"
       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:database.properties"/>

    <!--2.连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </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.alinu.dao"/>
    </bean>
</beans>
  • 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"
       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.扫描service下的包-->
    <context:component-scan base-package="com.alinu.service"/>

    <!--2.注入业务类-->
    <bean id="bookServiceImpl" class="com.alinu.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--3.声明式事务配置-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

5.SpringMVC层

5.1.项目添加框架支持

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5ZACYsxB-1598236362620)(/Users/chenzuwei/Library/Application Support/typora-user-images/image-20200824102257359.png)]

5.2.配置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">
    <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>

5.3.编写controller层

package com.alinu.controller;

import com.alinu.pojo.Book;
import com.alinu.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;

/**
 * @author Chenzuwei
 * @description
 * @createTime 2020-08-22 14:40
 * @since 1.0.0
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    private final String res = "display";

    @RequestMapping("/add")
    public String addBook(Book book) {
        int i = bookService.addBook(book);
        return "redirect:searchAll";
    }

    @RequestMapping("/delete")
    public String deleteBook(int bookId) {
        int i = bookService.deleteBook(bookId);
        return "redirect:searchAll";
    }

    @RequestMapping("/searchById")
    public String searchById(int bookId, Model model) {
        Book book = bookService.searchById(bookId);
        List<Book> books = new ArrayList<Book>();
        books.add(book);
        model.addAttribute("books", books);
        return res;
    }

    @RequestMapping("/searchAll")
    public String searchAll(Model model) {
        List<Book> books = bookService.searchAll();
        model.addAttribute("books", books);
        return res;
    }

    @RequestMapping("/update")
    public String updateBook(Book book){
        int i = bookService.updateBook(book);
        return "redirect:searchAll";
    }
}

5.4.创建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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.alinu.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>

5.5.创建applicationContext.xml

将spring-dao.xml,spring-service.xml和spring-mvc.xml导入applicationContext中

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

5.6.jsp页面

  • index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>index</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    h1 {
      text-align: center;
    }

    a {
      position: relative;
      left: 50%;
      margin: 200px 0 0 -55px;
    }
  </style>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1><small>首页</small></h1>
<hr>
<a href="${pageContext.request.contextPath}/book/searchAll" class="btn btn-primary">查看所有书籍</a>
</body>
</html>

  • display.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>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        .operation {
            width: 135px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row text-center">
        <div class="col-md-12">
            <div class="page-header">
                <h1><small>书籍展示系统</small></h1>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="row" style="margin: 20px 0">
                <div class="col-lg-3">
                    <div class="input-group">
                        <input type="text" id="searchById" class="form-control" placeholder="请输入书籍ID..."/>
                        <span class="input-group-btn">
                            <button class="btn btn-default" type="button" style="height: 34px" οnclick="searchById()">
                                <span class="glyphicon glyphicon-search"></span>
                            </button>
                        </span>
                    </div>
                </div>
                <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal"
                        data-whatever="新增书籍" data-url="${pageContext.request.contextPath}/book/add"
                        style="float: right">
                    新增书籍
                </button>
            </div>

            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th style="text-align: center">书籍ID</th>
                    <th style="text-align: center">书籍编号</th>
                    <th style="text-align: center">书籍名称</th>
                    <th style="text-align: center">书籍数量</th>
                    <th style="text-align: center">书籍描述</th>
                    <th style="text-align: center">操作</th>
                </tr>
                </thead>
                <tbody class="text-center">
                <c:forEach var="book" items="${books}">
                    <tr>
                        <td>${book.id}</td>
                        <td>${book.bookId}</td>
                        <td>${book.bookName}</td>
                        <td>${book.bookCount}</td>
                        <td>${book.description}</td>
                        <td class="operation">
                            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#myModal"
                                    data-whatever="修改书籍信息" data-url="${pageContext.request.contextPath}/book/update"
                                    οnclick="updateBookInfo('${book.bookId}','${book.bookName}','${book.bookCount}','${book.description}')">
                                修改
                            </button>
                            <button type="button" class="btn btn-danger" οnclick="deleteBook('${book.bookId}')">删除
                            </button>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document" style="top: 100px">
        <div class="modal-content">
            <div class="modal-header" style="text-align: center">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" οnclick="clearData()"><span
                        aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel"></h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" action="" method="post">
                    <div class="form-group" style="margin: 15px 15px 30px 30px">
                        <label for="bookId" class="col-md-3  control-label">书籍编号</label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="bookId" name="bookId" placeholder="书籍编号"
                                   required/>
                        </div>
                    </div>
                    <div class="form-group" style="margin: 15px 15px 30px 30px">
                        <label for="bookName" class="col-md-3 control-label">书籍名称</label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="bookName" name="bookName" placeholder="书籍名称"
                                   required/>
                        </div>
                    </div>
                    <div class="form-group" style="margin: 15px 15px 30px 30px">
                        <label for="bookCount" class="col-md-3 control-label">书籍数量</label>
                        <div class="col-md-8">
                            <input type="number" class="form-control" id="bookCount" name="bookCount" placeholder="书籍数量"
                                   required/>
                        </div>
                    </div>
                    <div class="form-group" style="margin: 15px 15px 30px 30px">
                        <label for="description" class="col-md-3 control-label">书籍描述</label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" id="description" name="description"
                                   placeholder="书籍描述"/>
                        </div>
                    </div>
                    <div class="form-group" style="margin: 40px 70px 30px 0; text-align: right">
                        <button type="button" class="btn btn-default" data-dismiss="modal" οnclick="clearData()"
                                style="margin-right: 10px">取消
                        </button>
                        <input type="submit" class="btn btn-info" value="确定"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<script>

    $('#myModal').on('show.bs.modal', function (event) {
        let button = $(event.relatedTarget) // Button that triggered the modal
        let recipient = button.data('whatever') // Extract info from data-* attributes
        let url = button.data('url') //获取请求路径

        var modal = $(this)
        modal.find('.modal-title').text(recipient)
        modal.find('.form-horizontal').attr('action', url)
    })

    function clearData() {
        $('.form-control').val("");
    }

    function updateBookInfo(bookId, bookName, bookCount, description) {
        $('#bookId').val(bookId);
        $('#bookName').val(bookName);
        $('#bookCount').val(bookCount);
        $('#description').val(description);
    }

    function deleteBook(bookId) {
        let r = window.confirm("确定删除?");
        if (r === true) {
            window.location = "${pageContext.request.contextPath}/book/delete?bookId=" + bookId
        }
    }

    function searchById() {
        let bookId = $('#searchById').val();
        let regex = /^[0-9]+$/;
        if (bookId === "") {
            window.location = "${pageContext.request.contextPath}/book/searchAll";
        } else if (regex.test(bookId)) {
            window.location = "${pageContext.request.contextPath}/book/searchById?bookId=" + bookId
            $("#searchById").val("");
        } else {
            alert("输入书号格式不正确!");
        }
    }
</script>
</body>
</html>

6.部署项目

最后配置好Tomcat服务器,将项目打包部署运行即可

如有问题,请联系作者:
作者qq:1397363448
vx:17596548515
作者邮箱:chenzuwei0817@foxmail.com
感谢观看,如果喜欢的话,请点赞收藏加转发三连噢!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值