MVC三层架构业务逻辑

用户==>Controller==>Service==>Dao==>数据库

重要:pom.xml

此项目要用的包

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.27</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.9</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.19.RELEASE</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.0</version>
</dependency>
<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.5</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.6</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.2.19.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.22</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.79</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.7</version>
</dependency>

解决静态资源导出问题

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
        <include>**/*.css</include>
      </includes>
      <filtering>false</filtering>
    </resource>
    <resource>
      <directory>src/main/resources</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
        <include>**/*.css</include>
      </includes>
      <filtering>false</filtering>
    </resource>
  </resources>
</build>

ssm框架整合

一、Spring层

1、配置dao层【spring-dao.xml】

  1. 关联数据库配置文件

    <context:property-placeholder location="classpath:db.properties"/>
  2. 连接池

    <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.yiyu.dao"/>
    </bean>
  5. JDBC配置文件【db.properties】

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?characterEncoding=UTF-8&serverTimezone=UTC
    jdbc.username=root
    jdbc.password=root
注意:

配置文件必须严格按照官方规范书写,否则会报 Access denied for user 'root'@'localhost' (using password: YES) 错误

2、配置service层【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"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--    1、扫描service下的包-->
    <context:component-scan base-package="com.yiyu.service"/>
    <!--    2、将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
    <bean id="bookServiceImpl" class="com.yiyu.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事务支持-->
<!--    结合AOP实现事务的织入-->
<!--    配置事务通知:-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        给那些方法配置事务-->
<!--        配置事务的传播特性:new propagation=-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.yiyu.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

二、SpringMVC层

配置mvc层【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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!--    1、注解驱动-->
    <mvc:annotation-driven>
<!--        解决乱码问题-->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" index="0"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--    2、静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--    3、扫描包-->
    <context:component-scan base-package="com.yiyu.controller"/>
    <!--    4、视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

三、MyBatis层

配置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">
<configuration>
<!--    日志功能-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<!--    起别名 Books 默认别名为 : books-->
    <typeAliases>
        <package name="com.yiyu.pojo"/>
    </typeAliases>
<!--    导入映射文件-->
    <mappers>
        <mapper class="com.yiyu.dao.BookMapper"/>
    </mappers>
</configuration>

四、整合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"
       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>

五、配置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">
<!--    DispatchServlet-->
    <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>
    </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 过时时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

六、至此框架整合完毕,开始写业务


业务

1、编写Book实体类

package com.yiyu.pojo;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Books {
    private int bookId;
    private String bookName;
    private int bookCounts;
    private String detail;
}

2、编写Book接口

package com.yiyu.dao;

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

import java.util.List;

public interface BookMapper {
    int addBook(Books books);
    int deleteBookById(int id);
    int updateBook(Books books);
    Books queryBookById(int id);
    List<Books>queryAllBook();
    Books queryBookByName(@Param("bookName") String bookName);
}

3、编写Book接口对应的SQL

<?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">
<!--namespace 命名空间 : 对应一个接口-->
<mapper namespace="com.yiyu.dao.BookMapper">
    <insert id="addBook" parameterType="books">
        insert into books(bookName,bookCounts,detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>
    <delete id="deleteBookById" parameterType="int">
        delete
        from books
        where bookId=#{id};
    </delete>
    <update id="updateBook" parameterType="books">
        update books
        set bookName = #{bookName},bookCounts = #{bookCounts},detail= #{detail}
        where bookId=#{bookId};
    </update>
    <select id="queryBookById" parameterType="int" 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、编写BookService接口

package com.yiyu.service;

import com.yiyu.pojo.Books;
import java.util.List;

public interface BookService {
    int addBook(Books books);
    int deleteBookById(int id);
    int updateBook(Books books);
    Books queryBookById(int id);
    List<Books> queryAllBook();
    Books queryBookByName(String bookName);
}

5、编写BookService实现类

package com.yiyu.service;

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

import java.util.List;

public class BookServiceImpl implements BookService{

    //service 调dao层 : 组合Dao
    private BookMapper bookMapper;

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

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

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

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

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

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

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

6、编写Controller层

package com.yiyu.controller;

import com.alibaba.fastjson.JSON;
import com.yiyu.pojo.Books;
import com.yiyu.service.BookService;
import com.yiyu.service.BookServiceImpl;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

    //查询全部的书籍,并且返回到一个书籍展示页面
    @RequestMapping("allBook")
    public String list(Model model){
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("list",books);
        return "allBook";
    }
    @ResponseBody
    @RequestMapping("allBook2")
    public String list(){
        return JSON.toJSONString(bookService.queryAllBook());
    }
//    跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook=>"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";  //重定向到我们的@RequestMapping("allBook")
    }

    @RequestMapping("/addBook2")
    public String addBook2(Books books){
        System.out.println("books=>"+books);
        bookService.addBook(books);
        return "redirect:/index.html";  //重定向到我们的@RequestMapping("allBook")
    }

//    跳转到修改页面
//    restful风格接收参数
    @RequestMapping("/toUpdateBook/{id}")
    public String toUpdatePaper(@PathVariable("id") int id, Model model){
        System.out.println("id=>"+id);
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "updateBook";
    }
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println("books=>"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }
    @RequestMapping("/deleteBook")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);
        System.err.println("queryBookByName=>"+books);
        List<Books>list=new ArrayList<>();
        list.add(books);
        if(books==null){
            list= bookService.queryAllBook();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list",list);
        return "allBook";
    }
}
  • 运用RestFul风格传参
  • 加上@ResponseBody注解表示改方法不以视图的方式返回,以String类型返回给前端

编写前端页面

1、首页【index.jsp】

<%--
  Created by IntelliJ IDEA.
  User: 31833
  Date: 2022/1/24
  Time: 20:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
    <style>
        a{
            text-decoration: none;
            color: black;
            font-size: 18px;
        }
        h3{
            width: 180px;
            height: 38px;
            text-align: center;
            margin: 100px auto;
            line-height: 38px;
            background: #51acd7;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<h3>
    <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>
</body>
</html>

2、显示所有书籍以及删除书籍【allBook.jsp】

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 31833
  Date: 2022/1/24
  Time: 21:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示</title>
    <link rel="stylesheet" href="../../css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-information">
                <h1>
                    <small>书籍列表 —————— 显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <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="form-check-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
                <span style="color: red;font-weight: bold">${error}</span>
                <input style="width: 200px;display: inline-block" type="text" name="queryBookName"
                       placeholder="请输入要查询的书籍名称" class="form-control">
                <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">
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名称</th>
                    <th>书籍数量</th>
                    <th>书籍详情</th>
                    <th>操作</th>
                </tr>
                <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> &nbsp;
                            | &nbsp;
                            <a href="${pageContext.request.contextPath}/book/deleteBook?id=${book.bookId}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
            </table>
        </div>
    </div>
</div>
</body>
</html>

3、添加书籍【addBook.jsp】

<%--
  Created by IntelliJ IDEA.
  User: 31833
  Date: 2022/1/25
  Time: 15:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增书籍</title>
    <link rel="stylesheet" href="../../css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-information">
                <h1>
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        <label for="bookName">书籍名称:</label>
        <input type="text" id="bookName" name="bookName" class="form-control" required>
        <label for="bookName">书籍数量:</label>
        <input type="text" id="bookCounts" name="bookCounts" class="form-control" required>
        <label for="bookName">书籍描述:</label>
        <input type="text" id="detail" name="detail" class="form-control" required>
        <input type="submit" class="btn btn-primary" value="添加">
    </form>
</div>
</body>
</html>

4、修改书籍【updateBook.jsp】

<%--
  Created by IntelliJ IDEA.
  User: 31833
  Date: 2022/1/25
  Time: 16:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
    <link rel="stylesheet" href="../../css/bootstrap.css">
</head>
<body>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%--    出现的问题:我们提交了修改的SQL请求,但是修改失败,初次考虑,是事务问题,配置完毕事务,依旧失败!--%>
<%--    看一下SQL语句,能否执行成功:SQL执行失败,修改为完成--%>
<%--    前端传递隐藏域--%>
    <input type="hidden" name="bookId" value="${books.bookId}">
    <label for="bookName">书籍名称:</label>
    <input type="text" id="bookName" name="bookName" class="form-control" value="${books.bookName}" required>
    <label for="bookName">书籍数量:</label>
    <input type="text" id="bookCounts" name="bookCounts" class="form-control" value="${books.bookCounts}" required>
    <label for="bookName">书籍描述:</label>
    <input type="text" id="detail" name="detail" class="form-control" value="${books.detail}" required>
    <input type="submit" class="btn btn-primary" value="修改">
</form>
</body>
</html>

有错必究,欢迎广大猿友前来讨论!

最后修改:2023 年 01 月 31 日
如果觉得我的文章对你有用,请随意赞赏