Java學習筆記:SpringMVC+MyBatis實現簡單的增刪改查【IDEA版】


1.前言

這段日子一直在學習Spring和SpringMVC的相關知識,看了不少的視頻和文章之后,想着動手實操一下。同時也記錄一下學習的過程和成果。
由於剛剛接觸不久,屬於新手,有錯的話,可以指正,俺的態度就是:立馬改!

2.項目配置說明

2.1. 首先我使用的工具:

開發工具 版本
jdk 1.8
IDEA 2019.2
Tomcat 8.0.53
MySQL 8.0.13
Maven 3.5.4

2.2. 建立數據庫表:說明:這里我只建立了一張單表student,如果說需要多表查詢,可以自己在此基礎上自由擴展。

  ```
  DROP TABLE IF EXISTS `student`;
  CREATE TABLE `student`  (
    `id` int(10) NOT NULL AUTO_INCREMENT,
    `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    `sex` varchar(4) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    `birth` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    `department` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    `address` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE
   ) ENGINE = InnoDB AUTO_INCREMENT = 939 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
   -- ----------------------------
   -- Records of student
   -- ----------------------------
   INSERT INTO `student` VALUES (904, '張三', '男', '1990', '英語系', '遼寧省阜新市');
   INSERT INTO `student` VALUES (905, '李四', '女', '1991', '英語系', '福建省廈門市');
   INSERT INTO `student` VALUES (906, '王五', '男', '1988', '計算機系', '湖南省衡陽市');
   INSERT INTO `student` VALUES (915, '陳六', '男', '1997', '計算機系', '河南省鄭州市');
   INSERT INTO `student` VALUES (936, '候七', '男', 'sda', '撒大聲地', '北京市');
   INSERT INTO `student` VALUES (938, '鍾八', '女', '1999-05-18', '園藝園林', '上海市');
   INSERT INTO `student` VALUES (939, '趙九', '男', 'sda', '撒大聲地', '深圳市');

   SET FOREIGN_KEY_CHECKS = 1;

  ```

2.3.搭建springMVC項目框架,使用Maven做jar包管理。

2.3.1.依次點擊IDEA 的File --> NeW --> Project...,選擇左邊欄的Maven菜單,之后選中 Create from archetype以及 選中下面的maven-archetype-webapp,選中 之后你可以看到下面出現了一行英文:A simple Java web application. 如下圖:

2.3.2.填寫完項目名相關信息之后,就是maven本地倉庫的設置,將下圖的選為你的本地倉庫,User settings file 文件為本地倉庫的conf文件夾下的settings.xml。

2.3.3 .經過maven項目創建完成后生成的項目文件夾骨架為:

我們在此基礎上創建出完整的SpringMVC常見的項目文件骨架:

    1. 在main文件夾下創建 java 文件夾和resources文件夾。之后在java文件夾下創建包。一般我們創建包都是域名的反寫,比如baidu.com,我們創建文件夾就是 com.baidu。(注意:不是文件夾的名字是com.baidu,而是com文件夾里有個baidu文件夾.)
    2.這里我用com.itheima吧。在itheima文件夾下創建controller(控制層),service(業務層),dao(數據訪問層),entity(實體層)mapper(SQL映射文件層),再加上一個utils(工具層)(可創建可不創建,自由選擇)
    3.resources 文件夾創建一個spring文件夾和jdbc.properties文件。webapp下創建static和views兩個文件夾,views文件夾下創建student文件夾。最后在student文件夾下創建list.jsp文件.

2.3.4.將java文件夾設為sources文件(做法是選中java文件夾,右鍵選擇Make Directory as --> Sources Root),同理 sources 設為 Resources Root.

2.3.5. 添加框架支持(Add Frameworks Support),選中項目文件夾,右鍵點擊Add Frameworks Support,然后選擇spring下的SpringMVC。靜待資源下載完成。下載完成后將生成的dispatch-servlet.xml和applicationContext.ml移到resources/spring文件夾下,並重新命名為:spring-mvc.xml和spring-mybatis.xml。

讓我們再看一遍項目結構。

3.項目xml配置(開始貼代碼了)

1.pox.xml文件中添加項目依賴和插件.

  ```
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>SSMProDemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SSMProDemo Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <spring.version>4.3.0.RELEASE</spring.version>
    </properties>

    <dependencies>
      <!--Spring框架核心庫 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <!-- Spring MVC -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <!-- aspectJ AOP 織入器 -->
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.9</version>
      </dependency>
      <!--mybatis-spring適配器 -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
      </dependency>
      <!--Spring java數據庫訪問包,在本例中主要用於提供數據源 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <!--mysql數據庫驅動 TODO:注意:如果你的mysql 是5.x,替換相應的jar包.換成5.x.x的版本. -->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
      </dependency>
      <!--log4j日志包 -->
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.6.1</version>
      </dependency>
      <!-- mybatis ORM框架 -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
      </dependency>
      <!-- JUnit單元測試工具 -->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
      </dependency>
      <!--c3p0 連接池 -->
      <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
      </dependency>
      <!-- JSTL -->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
      </dependency>
      <!-- Servlet核心包 -->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
      </dependency>
      <!--JSP -->
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
      </dependency>
      <!-- jackson -->
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.2</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.2</version>
      </dependency>
      <!--JSR303 -->
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.2.Final</version>
      </dependency>
      <!--文件上傳 -->
      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
      </dependency>
      <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
      </dependency>

      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
      </dependency>



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


      <plugins>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.1</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </project>
  ```

說明: 標簽中的resource必須要寫,這關乎着mapper文件夾下的xml文件經編譯后能不能在target文件夾下生成的問題。如果無法生成,后面xml配置就會找不到路徑文件。

2.web.xml文件配置:

  ```
      <?xml version="1.0" encoding="UTF-8"?>
        <web-app id="WebApp_ID" version="3.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://java.sun.com/xml/ns/javaee"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
           http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

      <!--  加載spring和mybatis的配置文件 -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/spring-mybatis.xml</param-value>
      </context-param>

      <!-- 使用ContextLoaderListener初始化Spring容器 -->
      <!--若沒有指定其他參數,默認查找的配置文件位置是:/WEB-INF/applicationContext.xml  -->
      <listener>
          <description>Spring容器加載監聽器</description>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

      <!-- 配置springmvc核心控制器 -->
      <!-- spring MVC servlet -->
      <servlet>
          <servlet-name>SpringMVC</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <init-param>
              <description>springMVC</description>
              <param-name>contextConfigLocation</param-name>
              <param-value>classpath:spring/spring-mvc.xml</param-value>
          </init-param>
          <!-- 啟動動優先級,越小越早加載 -->
          <load-on-startup>1</load-on-startup>
      </servlet>
      <!-- Servlet訪問的路徑映射,所有的訪問都必須經過調度用的前置控制器 -->
      <servlet-mapping>
          <servlet-name>SpringMVC</servlet-name>
          <url-pattern>/</url-pattern>
      </servlet-mapping>

      <!--編碼過濾器 -->
      <filter>
          <description>字符集過濾器</description>
          <filter-name>encodingFilter</filter-name>
          <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
          <init-param>
              <description>字符集編碼</description>
              <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>

      <welcome-file-list>
          <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
  </web-app>
  ```

3.spring-mvc.xml

  ```
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
               xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.3.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.3.xsd" >


            <!-- 自動掃描該包,使springmvc認為包下用了@Controller注解的類是控制器 -->
            <context:component-scan base-package="com.itheima.controller" />

            <!-- 2.配置注解的處理器映射器和處理器適配器 -->
            <!-- <mvc:annotation-driven /> 是一種簡寫形式,完全可以手動配置替代這種簡寫形式,簡寫形式可以讓初學者
                快速應用默認配置方案。<mvc:annotation-driven /> 會自動注冊DefaultAnnotationHandlerMapping與
                AnnotationMethodHandlerAdapter 兩個bean,是spring MVC為@Controllers分發請求所必須的。 -->
            <mvc:annotation-driven />

            <!--    &lt;!&ndash; 3.Spring MVC不處理靜態資源  &ndash;&gt;-->
            <!-- 靜態資源映射 -->
            <mvc:resources mapping="/static/js/**" location="static/js/"></mvc:resources>
            <mvc:resources mapping="/static/css/**" location="static/css/"></mvc:resources>
            <mvc:resources mapping="/static/images/**" location="static/images/"></mvc:resources>
            <mvc:resources mapping="/static/My97DatePicker/**" location="static/My97DatePicker/"></mvc:resources>
            <!--    <mvc:default-servlet-handler />-->
            <!-- 4.配置內部視圖解析器 -->
            <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前后綴 -->
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/views/" />
                <property name="suffix" value=".jsp" />
            </bean>



  </beans>            



  ```

4.spring-mybatis.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:p="http://www.springframework.org/schema/p"
               xmlns:context="http://www.springframework.org/schema/context"
               xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
               xmlns:mvc="http://www.springframework.org/schema/mvc"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.3.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

            <!-- 1.引入屬性文件 -->
            <context:property-placeholder location="classpath:jdbc.properties" />

            <!-- 2.自動掃描service包(自動注入) -->
            <context:component-scan base-package="com.itheima.service" />

            <!-- ========================================配置數據源========================================= -->
            <!-- 3.配置C3P0數據源 -->
            <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
                  destroy-method="close">
                <!--驅動類名 -->
                <property name="driverClass" value="${mysql.driver}" />
                <!-- url -->
                <property name="jdbcUrl" value="${mysql.url}" />
                <!-- 用戶名 -->
                <property name="user" value="${mysql.user}" />
                <!-- 密碼 -->
                <property name="password" value="${mysql.password}" />
                <!-- 當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數 -->
                <property name="acquireIncrement" value="${mysql.acquireIncrement}"></property>
                <!-- 初始連接池大小 -->
                <property name="initialPoolSize" value="${mysql.initialPoolSize}"></property>
                <!-- 連接池中連接最小個數 -->
                <property name="minPoolSize" value="${mysql.minPoolSize}"></property>
                <!-- 連接池中連接最大個數 -->
                <property name="maxPoolSize" value="${mysql.maxPoolSize}"></property>

            </bean>

            <!-- ========================================針對myBatis的配置項============================== -->
            <!-- 4.配置sqlSessionFactory -->
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!-- 實例化sqlSessionFactory時需要使用上述配置好的數據源以及SQL映射文件 -->
                <!-- 數據源 -->
                <property name="dataSource" ref="dataSource" />
                <!-- sql映射文件路徑 -->
                <!-- 自動掃描com/demo/mapping/目錄下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置
                value="classpath:com/demo/mapping/*.xml"指的是classpath(類路徑)下com.demo.mapping包中的所有xml文件 -->
                <property name="mapperLocations" value="classpath:com/itheima/mapper/*.xml" />
            </bean>

            <!-- 5.配置掃描器  -->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <!-- 掃描com.demo.dao這個包以及它的子包下的所有映射接口類 -->
                <property name="basePackage" value="com.itheima.dao" />
                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
            </bean>

            <!-- ========================================配置事務============================== -->
            <!-- 6.聲明式事務管理 -->
            <!--定義事物管理器,由spring管理事務 -->
            <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <!-- 配置數據源 -->
                <property name="dataSource" ref="dataSource" />
            </bean>


        </beans>      

  ```

4.實現業務邏輯

首先我們先從控制層寫起。一般來說,客戶端發來的請求,從控制層開始處理,控制層調用service層的邏輯代碼,而service層實際上是接口層,我們在serviceImpl包下會實現這些接口,也就是間接調用了實現層的方法。而實現層會調用數據訪問層(dao)的接口。最終會和mapper文件中的SQL映射連接起來。

1.首先我們在entity 創建Student 實體類,此類是數據庫student表的對應類,添加對應的get/set方法,千萬記住,務必要添加無參構造方法。不然項目后面運行的時候可能出現讓你摸不到頭腦的錯誤。其次,再創建一個Message類,此類數據庫不做映射,其用途只是封裝返回消息的類。

package com.itheima.entry;

/**
* @Author:Duanzhenbiao
* @Date:2020/11/17
* @Description:
*/

public class Student {

    private Integer id; // 學生ID

    private String name ; // 學生姓名

    private String sex ; // 學生性別

    private String birth; // 學生生日

    private String  department; // 學生所屬部門.

    private String address ; // 學生所在地址

    // 無參構造
    public Student() { }

    public Student(String name, String sex, String birth, String department, String address) {
        this.name = name;
        this.sex = sex;
        this.birth = birth;
        this.department = department;
        this.address = address;
    }

    public Student(Integer id, String name, String sex, String birth, String department, String address) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.birth = birth;
        this.department = department;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", birth='" + birth + '\'' +
                ", department='" + department + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

}

Message消息類

package com.itheima.entry;

import java.util.HashMap;
import java.util.Map;

public class Message {
    // 封裝的消息類 : 給前端返回json數據時用的消息類. (注:該類,數據庫表不做映射.)

    //狀態碼 200-成功  100-失敗
    private int code;

    //提示信息
    private String msg;

    public Message() { }

    public Message(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Message(int code, String msg, Map<String, Object> data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    //用戶要返回給瀏覽器的數據
    private Map<String, Object> data = new HashMap<String, Object>();

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Message{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}


2.我們首先在controller層中創建studentController類 ,service層創建studentService接口,dao層創建studentDao接口,mapper創建studentMapper.xml文件。service文件夾下的Impl文件夾中創建studentServiceImpl類並繼承studentService,重寫service接口方法。

3.增刪改查我也不細說了,直接貼代碼,運行吧。

studentController層:

package com.itheima.controller;

import com.itheima.entry.Message;
import com.itheima.entry.Student;
import com.itheima.service.StudentService;
import com.itheima.util.Util;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author:Duanzhenbiao
 * @Date:2020/11/17
 * @Description: 學生表的增刪改查.
 */

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;


    // 獲取所有數據
    @RequestMapping("/list")
    public String selectAllStudents(Model model, @RequestParam(required=false,defaultValue="1") int page){
        // 每頁的條數
        int count = 5;
        // 每頁的數據
        List<Student> ls = studentService.selectAllStudents(page,count);
        // 該學生表的總學生人數.
        Integer total = studentService.getStudentTotal();
        model.addAttribute("current_page",page);//當前頁
        model.addAttribute("total",total); // 總數量
        model.addAttribute("count",count);// 每頁的數量
        model.addAttribute("students",ls);// 每頁的學生數據.
        return "student/list";
    }

    /**
     * 添加學生對象
     * @param student
     * @return
     */
    //添加數據
    @RequestMapping(value ="/add",produces="text/plain;charset=UTF-8") // 設置UTF-8 是為了返回時網頁能正常顯示中文.
    @ResponseBody
    public  String insertOneStudent(Student student){
        System.out.println( student);
        int result = studentService.insertOneStudent(student);
        String  res = result == 1 ? "{'status':200,'response':'添加成功'}":"{'status':100,'response':'添加失敗'}";
        System.out.println(res);
        return res;
    }

    /**
     * 編輯學生對象
     * @param student
     * @return
     */
    // 編輯數據,限定訪問方法.
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Message updateStudent(Student student){
        // 消息實例,備用.
        Message msg = new Message();
        // 檢測傳進來的參數是否為空值。
        System.out.println(student);
        boolean flag = Util.checkStudentNull(student);
        if (!flag){
            msg.setCode(100);
            msg.setMsg("fail");
            return msg;
        }
        // 簡單限制之后,更新數據庫
        int result = studentService.updateStudent(student);
        if(result == 1){
            msg.setCode(200);
            msg.setMsg("success");
        }
        return msg;
    }

    /**
     *  刪除 student
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Message deleteStudent(@RequestParam(value = "id" ,required = true) int id){
        // 消息實例,備用.
        Message msg = new Message();
        // 數據庫刪除數據
        int result = studentService.deleteStudent(id);
        if(result == 1){
            msg.setCode(200);
            msg.setMsg("success");
        }else{
            msg.setCode(100);
            msg.setMsg("fail");
        }
        return msg;
    }





    @RequestMapping(value = "/getStudentById")
    @ResponseBody
    public Message selectStudentById(@RequestParam(value = "editID" ,required = true) int editID){
        // 實例化消息實例
        Message msg = new Message();
        // 查詢對應的student數據
        Student student = studentService.selectStudentById(editID);
        if(student == null) {
            msg.setCode(100);
            msg.setMsg("fail");
            return msg;
        }else{
            msg.setCode(200);
            msg.setMsg("success");
            msg.getData().put("data",student);
        }
        System.out.println(msg);
        return msg;

    }

}

studentService層:

package com.itheima.service;

import com.itheima.entry.Student;

import java.util.List;


public interface StudentService {

    // 查詢所有學生
    List<Student> selectAllStudents(int page,int count);

    // 添加一位學生
    int insertOneStudent(Student stu);

    // 查詢該表總共有多少條數據
    int getStudentTotal();

    // 更新數據庫的某條數據
    int updateStudent(Student student);

    // 通過ID查詢student
    Student selectStudentById(int editID);

    // 通過ID刪除對象
    int deleteStudent(int id);
}

studentServiceImpl層:

package com.itheima.service.Impl;

import com.itheima.dao.StudentDao;
import com.itheima.entry.Student;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:Duanzhenbiao
 * @Date:2020/11/17
 * @Description:
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;


    @Override
    public List<Student> selectAllStudents(int page, int count) {
        int skip = (page-1)*count;
        return studentDao.selectAllStudents(skip,count);
    }


    // 添加一個學生
    @Override
    public int insertOneStudent(Student stu) {
        return studentDao.insertOneStudent(stu);
    }

    // 查詢學生表總共有多少位學生.
    @Override
    public int getStudentTotal() {
        return studentDao.getStudentTotal();
    }

    // 更新數據庫某條數據
    @Override
    public int updateStudent(Student student) {
        return studentDao.updateStudent(student);
    }


    // 通過ID查詢student
    @Override
    public Student selectStudentById(int editID) {
        return studentDao.selectStudentById(editID);
    }

    @Override
    public int deleteStudent(int id) {
        return studentDao.deleteStudent(id);
    }
}

studentDao 層

package com.itheima.dao;

import com.itheima.entry.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @Author:Duanzhenbiao
 * @Date:2020/11/17
 * @Description:
 */

public interface StudentDao {

    // 查詢所有學生接口
    List<Student> selectAllStudents(@Param("skip") int skip, @Param("count") int count);

    // 添加一位學生.
    int insertOneStudent(Student stu);

    // 獲取學生總共有多少條數據.
    int getStudentTotal();

    // 更新數據庫中某條數據
    int updateStudent(Student student);

    // 通過ID查詢相應對象數據
    Student selectStudentById(int id);

    // 通過 id刪除相應的對象數據
    int deleteStudent(int id);
}

還剩最重要的mapper文件:studentMapper.xml

<?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.itheima.dao.StudentDao">
    <!--查詢用戶信息並分頁 -->
    <select id="selectAllStudents" resultType="com.itheima.entry.Student">
       select * from student limit #{skip},#{count}
    </select>

    <!-- 添加一位學生   -->
    <insert id="insertOneStudent"  parameterType="com.itheima.entry.Student" >
        insert into student(name,sex,birth,department,address) value(#{name},#{sex},#{birth},#{department},#{address})
    </insert>

    <!-- 獲取學生表學生的總人數   -->
    <select id="getStudentTotal" resultType="java.lang.Integer">
        select count(*) from student
    </select>

    <!-- 通過ID更新數據   -->
    <update id="updateStudent" parameterType="com.itheima.entry.Student">
        update student set name = #{name},sex = #{sex},birth = #{birth},department = #{department},address = #{address} where id = #{id}
    </update>

    <!--  通過ID查詢對應的student  -->
    <select id="selectStudentById" resultType="com.itheima.entry.Student" parameterType="int">
        select * from  student where id = #{id}
    </select>

    <!-- 通過ID刪除對應數據   -->
    <delete id="deleteStudent" parameterType="int" >
        delete  from student where id = #{id}
    </delete>

</mapper>

原本我是想增、刪、改、查敘述的,結果貼的代碼看起來很多,所以臨時改變了方式。上面的代碼實現了后端的事情,可以用postman測試一下接口,接着就是前端的事了。
前端從index.jsp 頁面開始,跳轉到list.jsp頁面,在此頁面進行增刪改查,看看實際效果再貼代碼吧。

添加窗口

前端的list.jsp 頁面代碼:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="/static/css/bootstrap.min.css"  type="text/css" rel="stylesheet" />
    <link href="/static/css/main.css"  type="text/css" rel="stylesheet" />
    <link href="/static/css/pagination.css"  type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="/static/js/jquery-3.3.1.min.js" ></script>
    <script type="text/javascript" src="/static/js/bootstrap.min.js" ></script>
    <title>學生管理</title>
</head>
<body>
    <div class="main">
        <h2 class="title"><span>學生管理</span></h2>
        <%--  按鈕組      --%>
        <p class="Add_button">
            <button class="btn out" style="cursor: pointer" data-toggle="modal" data-target="#addModal">&nbsp;添加&nbsp;</button>
<%--            <button class="btn out" onclick="return submitForm();"> 批量刪除</button>--%> <!--批量刪除功能未實現.-->
        </p>
        <%--  表單      --%>
        <form action="deleteUsers" method="post">
            <table border="1" width="100%" class="tab">
                <tr>
                    <th><input type="checkbox" id="chkAll"></th>
                    <th>姓名</th>
                    <th>性別</th>
                    <th>出生日期</th>
                    <th>部門</th>
                    <th>地址</th>
                    <th>操作</th>
                </tr>
                <c:forEach var="student" items="${students}">
                    <tr>
                        <th><input type="checkbox" name="student_id" value="${student.id}"></th>
                        <td>${student.name}</td>
                        <td>${student.sex}</td>
                        <td>${student.birth}</td>
                        <td>${student.department}</td>
                        <td>${student.address}</td>

                        <td>
                            <a href="javascript:void(0)" class="abtn" data-toggle="modal" data-target="#editModal"  onclick="editStudent(${student.id})">編輯</a>
                            <a href="javascript:void(0)" class="abtn" data-toggle="modal" data-target="#deleteModal" onclick="deleteStudent(${student.id})">刪除</a>
                        </td>
                    </tr>
                </c:forEach>

            </table>
            <div id="pager"></div>

        </form>
    </div>


    <%--添加模態框--%>
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">新增學生</h4>
                </div>
                <div class="modal-body">
                    <form action="">
                        <div class="input-group">
                            <span class="input-group-addon" id="basic-addon1">姓名</span>
                            <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1" id="username">
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon" id="basic-addon2">性別</span>
                            <label style="margin-left: 25px; padding-top: 5px;cursor: pointer;"><input type="radio" name="sex" value="男">男生</label>
                            <label style="margin-left: 25px; padding-top: 5px;cursor: pointer;"><input type="radio" name="sex" value="女">女生</label>
                            </div>
                        <div class="input-group">
                            <span class="input-group-addon" id="basic-addon3">生日</span>
                            <input type="text" class="form-control" placeholder="生日" aria-describedby="basic-addon1" id="birthday">
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon" id="basic-addon4">部門</span>
                            <input type="text" class="form-control" placeholder="部門" aria-describedby="basic-addon1" id="department">
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon" id="basic-addon5" >地址</span>
                            <input type="text" class="form-control" placeholder="地址" aria-describedby="basic-addon1" id="address">
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                    <button type="button" class="btn btn-primary" onclick="addSubmit();">確認</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>


    <%--編輯模態框--%>
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true" >
        <div class="modal-dialog" >
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="editModalLabel">編輯學生</h4>
                </div>
                <div class="modal-body">
                    <form action="">
                        <div class="input-group">
                            <span class="input-group-addon">姓名</span>
                            <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1" id="edit_username">
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon">性別</span>
                            <label style="margin-left: 25px; padding-top: 5px;cursor: pointer;"><input type="radio" name="edit_sex" value="男">男生</label>
                            <label style="margin-left: 25px; padding-top: 5px;cursor: pointer;"><input type="radio" name="edit_sex" value="女">女生</label>
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon">生日</span>
                            <input type="text" class="form-control" placeholder="birthday" aria-describedby="basic-addon1" id="edit_birthday">
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon">部門</span>
                            <input type="text" class="form-control" placeholder="department" aria-describedby="basic-addon1" id="edit_department">
                        </div>
                        <div class="input-group">
                            <span class="input-group-addon">地址</span>
                            <input type="text" class="form-control" placeholder="address" aria-describedby="basic-addon1" id="edit_address">
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                    <button type="button" class="btn btn-primary" onclick="editSubmit();">確認</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

    <%--刪除模態框--%>
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog" >
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="deleteModalLabel">刪除學生</h4>
                </div>
                <div class="modal-body">
                    <p>您確定要刪除此條數據嗎?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                    <button type="button" class="btn btn-primary" onclick="deleteSubmit();">確認</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>



    <!--分頁 -->
    <script type="text/javascript" src="/static/js/jquery.pagination.js" ></script>
    <script type="text/javascript">
        //初始化分頁組件  <!--因為此處有$ {} 屬於jstl,無法提取到js中 ,-->
        var total=${total};// 學生總人數
        var count=${count}; // 每頁的數量
        var page=${current_page}; // 當前頁
        $("#pager").pagination(total, {
            items_per_page:count,
            current_page:page - 1 ,
            next_text:"下一頁",
            prev_text:"上一頁",
            num_edge_entries:2,
            load_first_page:false,
            callback:handlePaginationClick
        });
        //回調方法
        function handlePaginationClick(new_page_index, pagination_container){
            location.href="list?page="+(new_page_index+1);
        }

    </script>
    <!-- 對數據的增刪改查都提取到此js中   -->
    <script type="text/javascript" src="/static/js/student-list.js" ></script>

</body>
</html>

配套的student-list.js


$(document).ready(function(){
    //全選/取消全選
    $("#chkAll").click(function(){
        var checked=$("#chkAll").prop("checked");
        $("input[name='student_id']").prop("checked",checked);
    })
})


// // 批量刪除按鈕 :太懶了,不想做了.
// function submitForm(){
//     if($("input[name='student_id']:checked").length==0){
//         alert("請選擇要刪除的記錄!");
//         return false;
//     }
//     return true;
// }

// 添加提交方法
function addSubmit() {
    var username = $("#username").val().replace(/^\s+|\s+$/g, ""); // 用戶名(去除兩邊空格)
    var sex = $("input[name='sex']:checked").val(); // 用戶性別(去除兩邊空格)
    var birthday = $("#birthday").val().replace(/^\s+|\s+$/g, ""); // 用戶生日(去除兩邊空格)
    var department = $("#department").val().replace(/^\s+|\s+$/g, ""); // 用戶部門(去除兩邊空格)
    var address = $("#address").val().replace(/^\s+|\s+$/g, ""); // 用戶部門(去除兩邊空格)

    // 這里只做簡單的非空限制
    if(username.length == 0 || sex == undefined || birthday.length == 0 || department == 0 || address == 0){
        alert("表單中字段不能為空!");// 簡單的alert()提示框.
        return false;
    }
    // ajax 向后台發起請求.
    $.ajax({
        url: "/student/add/?" + "name=" +username +"&sex="+sex + "&birth=" + birthday +"&department="+ department+"&address=" +address,
        type: "GET",
        timeout: 3000,
        success: function (data) {
            alert(data);
            // 成功之后,關閉模態框,數據清零
            $("#addModal").modal("hide");
            $("#addModal input").val("")
            // 添加成功后刷新頁面
            window.setTimeout(function () {
                window.location.reload();
            },2000);
        }, error: function (e) {
           alert("添加失敗.")
        }
    });
}

// 獲取要編輯的數據ID,隱藏在打開的模態框里。
function editStudent(editID){
    // 將要編輯的數據ID,隱藏在編輯模態框的 div 中.
   $("#editModal").attr("value",editID);
   // 獲取該條數據
   $.ajax({
       url: "/student/getStudentById/?editID="+editID ,
       type: "GET",
       timeout: 3000,
       dataType:'json',
       success: function (json) {
           if(json["code"] == 200){
                // 數據填充
               $("#edit_username").val(json["data"]["data"]["name"]);

               if(json["data"]["data"]["sex"] == "男"){  // 性別賦值
                   $("input[name='edit_sex']").eq(0).attr("checked",true);
               }else{
                   $("input[name='edit_sex']").eq(1).attr("checked",true);
               }

               $("#edit_birthday").val(json["data"]["data"]["birth"]);
               $("#edit_department").val(json["data"]["data"]["department"]);
               $("#edit_address").val(json["data"]["data"]["address"]);
           }else{
               alert(json["msg"])
           }
       }, error: function (e) {
           alert("添加失敗.")
       }
   })

}

// 確認編輯之后,觸發方法.
function editSubmit() {
    var editID = $("#editModal").attr("value");
    var name = $("#edit_username").val().replace(/^\s+|\s+$/g, ""); // 用戶名(去除兩邊空格)
    var sex = $("input[name='edit_sex']:checked").val(); // 用戶性別(去除兩邊空格)
    var birth = $("#edit_birthday").val().replace(/^\s+|\s+$/g, ""); // 用戶生日(去除兩邊空格)
    var department = $("#edit_department").val().replace(/^\s+|\s+$/g, ""); // 用戶部門(去除兩邊空格)
    var address = $("#edit_address").val().replace(/^\s+|\s+$/g, ""); // 用戶部門(去除兩邊空格)




    // 這里只做簡單的非空限制
    if(name.length == 0 || sex.length == 0 || birth.length == 0 || department == 0 || address == 0){
        alert("表單中字段不能為空!");// 簡單的alert()提示框.
        return false;
    }

    var  form = new FormData();
    form.append("id",parseInt(editID));
    form.append("name",name);
    form.append("sex",sex);
    form.append("birth",birth);
    form.append("department",department);
    form.append("address",address);
    $.ajax({
        url: "/student/edit/",
        type: "POST",
        data: form,
        contentType: 'application/json',
        async: false,//同步上傳
        dataType:'json',
        success: function (data) {
            alert(data["code"])
        }, error: function (e) {
            console.log(e);
            alert('系統出現錯誤,即將自動刷新');
        }

    })
}

function deleteStudent(deleteID) {
    $("#deleteModal").attr("value",deleteID);
}

// 刪除確認事件
function deleteSubmit() {
    // 獲取要刪除的ID
    var id = $("#deleteModal").attr("value");
    // ajax請求
    var formData = new FormData();
    formData.append("id",id);
    $.ajax({
        url: "/student/delete/",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        async: false,
        dataType: 'json',
        success: function (data) {
            if(data["code"] == 200){
                alert("刪除成功");
                $("#deleteModal").modal("hide");
                // 兩秒后刷新頁面
                window.setTimeout(function () {
                    window.location.reload();
                },2000);

            }
        }, error: function (e) {
            alert('系統出現錯誤,即將自動刷新');
        }
    })


}

結尾:

項目代碼以及靜態資源文件地址 :
鏈接:https://pan.baidu.com/s/1fGz3OzxfHX5c1NzYR5rDhA 提取碼:n1z8


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM