SpringMVC学习:整合SSM框架

SpringMVC学习:整合SSM框架,第1张

前言

本章将通过一个图书管理案例,将之前所学到的MyBatis,Spring,SpringMVC的知识串起来,整合SSM框架。

使用的技术:

  • MySQL(8.0.28)
  • MyBatis (3.5.7)
  • Spring
  • SpringMVC
  • 页面展示部分用了一点儿BootStrap
  • Lombok

使用IDEA进行开发。

源码托管到了Gitee上:https://gitee.com/blossoming819/ssmbuild.git

1、搭建数据库
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,'从进门到进牢');
2、导入依赖

使用Maven构建项目,导入依赖更方便,只需在Maven项目中的pom.xml中添加配置即可,依赖可以在Maven仓库中获取到。

<dependencies>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.22version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.5version>
        dependency>
        
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.1version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>4.0.1version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.7version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.18version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.18version>
        dependency>
    dependencies>

为了避免资源或者配置找不到的问题,我们在Maven的配置里添加资源过滤,依然是在pom.xml中配置。

<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>
3、构建项目结构

首先需要新建一个图书类Books

package com.princehan.pojo;

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

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/19 12:51
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}
4、配置SSM框架

整合SSM要实现dao,service,controller三个方面

4.1、dao层

配置MyBatis


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="cacheEnabled" value="true"/>
    settings>
    <typeAliases>
        <package name="com.princehan.pojo"/>
    typeAliases>
    <mappers>
        <mapper class="com.princehan.dao.BookMapper"/>
    mappers>
configuration>

编写连接数据库的配置文件

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

由于本案例使用的数据源为c3p0,所以前缀要加上jdbc,在测试过程中,发现不加会报错

配置dao层的spring,连接MyBatis


<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: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}"/>
    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.princehan.dao"/>
    bean>
beans>

编写BookMapper接口

package com.princehan.dao;

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

import java.util.List;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/19 12:57
 */
public interface BookMapper {
    int addBook(Books book);

    int deleteBookById(@Param("bookID") int id);

    int updateBook(Books book);

    Books queryBookById(@Param("bookID") int id);

    List<Books> queryAllBook();

    List<Books> queryBookByName(@Param("bookName") String name);

}

编写BookMapper接口的映射


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.princehan.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into books(bookName, bookCounts, detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    insert>
    <delete id="deleteBookById">
        delete
        from books
        where bookID = #{bookID}
    delete>
    <update id="updateBook" parameterType="Books">
        update books
        set bookName   = #{bookName},
            bookCounts = #{bookCounts},
            detail     = #{detail}
        where bookID = #{bookID}
    update>
    <select id="queryBookById" resultType="Books">
        select *
        from books
        where bookID = #{bookID}
    select>

    <select id="queryAllBook" resultType="Books">
        select *
        from books
    select>

    <select id="queryBookByName" resultType="Books">
        select *
        from books
        where bookName = #{bookName};
    select>
mapper>
4.2、service层

编写BookService接口

package com.princehan.service;

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

import java.util.List;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/19 13:17
 */
public interface BookService {
    int addBook(Books book);

    int deleteBookById(@Param("bookID") int id);

    int updateBook(Books book);

    Books queryBookById(@Param("bookID") int id);

    List<Books> queryAllBook();

    List<Books> queryBookByName(@Param("bookName") String name);
}

编写实现类

package com.princehan.service;

import com.princehan.dao.BookMapper;
import com.princehan.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/19 13:17
 */
@Service
//service注解表示这是一个bean,放入到了IOC容器
public class BookServiceImpl implements BookService {
    //业务层调用dao层
    private BookMapper bookMapper;

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

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

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

    @Override
    public int updateBook(Books book) {
        return bookMapper.updateBook(book);
    }

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

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

    @Override
    public List<Books> queryBookByName(String name) {
        return bookMapper.queryBookByName(name);
    }
}

配置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.princehan.service"/>

    




    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>
beans>
4.3、controller层

编写BookController接口

package com.princehan.controller;

import com.princehan.pojo.Books;
import com.princehan.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;

/**
 * @Description
 * @Author:PrinceHan
 * @CreateTime:2022/4/19 14:11
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    //自动装配
//    @Qualifier("BookServiceImpl")
    private BookService bookService;
}

配置spring的controller层


<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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.princehan.controller"/>

    <bean id="internalResourceViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>

beans>
4.4、整合dao,service,controller层

<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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:springmvc-servlet.xml"/>


beans>
5、功能实现 5.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>springmvcservlet-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>springmvcservlet-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>
5.2、编写主页index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页title>
    <style type="text/css">
        a {
            text-decoration: none;
            color: black;
            font-size: 18px;
        }
        h3 {
            width: 180px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background: deepskyblue;
            border-radius: 4px;
        }
    style>
head>
<body>
<h3><a href="${pageContext.request.contextPath}/book/allbook">书籍界面a>h3>
body>
html>

5.3、展示所有书籍allBook.jsp

编写展示页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>数据展示部分title>
    
    <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>
        div>
        <div class="col-md-4 column">div>
        <div class="col-md-4 column">
            <form class="form-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="form-control" placeholder="输入查询书名" required>
                <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="${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?id=${book.bookID}">更改a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.bookID}">删除a>
                        td>
                    tr>
                c:forEach>
                tbody>
            table>
        div>
    div>
div>
body>
html>

编写controller

    @RequestMapping("/allbook")
    public String queryAllBook(Model model) {
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("list", books);
        return "allBook";
    }

当点击书籍界面时,发动请求,service层获取到书籍列表,通过model携带数据,跳转到allBook.jsp页面。

5.4、修改书籍

这一功能的完成可以分为两步进行:跳转到修改页面,修改书籍,因此有两个请求。

修改指定的书籍需要传递书籍的id

<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookID}">更改a>

修改页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
    <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.bookID}">
        <div class="form-group">
            <label for="bookName">书籍名称label>
            <input type="text" id="bookName" name="bookName" value="${book.bookName}" class="form-controller" required>
        div>
        <div class="form-group">
            <label for="bookCounts">书籍数量label>
            <input type="text" id="bookCounts" name="bookCounts" value="${book.bookCounts}" class="form-controller" required>
        div>
        <div class="form-group">
            <label for="detail">书籍详情label>
            <input type="text" id="detail" name="detail" value="${book.detail}" class="form-controller" required>
        div>
        <div class="form-group">
            <input type="reset" value="重置">
            <input type="submit" value="提交">
        div>
    form>
div>
body>
html>

跳转到修改页面

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
        Books book = bookService.queryBookById(id);
        System.out.println(book);
        model.addAttribute("book", book);
        return "updateBook";
    }

修改数据,前端的数据通过name属性,被controller获取到,这里我们获取的是一个对象。

    @RequestMapping("/updateBook")
    public String updateBook(Books book) {
        bookService.updateBook(book);
        return "redirect:/book/allbook";
    }

修改后重定向至展示书籍的界面。

5.5、删除书籍

根据书籍id删除书籍,请求上需要携带id,这里使用的是Restful风格,更加简洁。

<a href="${pageContext.request.contextPath}/book/del/${book.bookID}">删除a>
    @RequestMapping("/del/{id}")
    public String deleteBook(@PathVariable int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allbook";
    }

删除后重定向至书籍展示页面。

5.6、添加书籍

依然可以分成两步进行,跳转到书籍增添页面,增添书籍。

书籍增添页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
    
    <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 for="bookName">书籍名称label>
            <input type="text" id="bookName" name="bookName" required>
        div>
        <div class="form-group">
            <label for="bookCounts">书籍数量label>
            <input type="text" id="bookCounts" name="bookCounts" required>
        div>
        <div class="form-group">
            <label for="detail">书籍详情label>
            <input type="text" id="detail" name="detail" required>
        div>
        <div class="form-group">
            <input type="submit" value="添加">
        div>
    form>
div>
body>
html>

跳转到书籍增添页面

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

增添书籍

    @RequestMapping("/addBook")
    public String addBook(Books book) {
        bookService.addBook(book);
        return "redirect:/book/allbook";
    }


5.7、查询书籍
<form class="form-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" value="${queryBookName} class="form-control" placeholder="输入查询书名" required>
    <input type="submit" value="查询" class="btn btn-primary">
form>
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model) {
        List<Books> books = bookService.queryBookByName(queryBookName);
        if (books.size() > 0) {
            model.addAttribute("list", books);
        } else {
            model.addAttribute("error", "查无此书");
        }
        model.addAttribute("queryBookName", queryBookName);
        return "allBook";
    }


6、小结

到此为止,通过这个小案例完成了SSM的整合,实现了对书籍的增删改查,希望能对大家有帮助。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/719558.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存