当前位置:网站首页>SSM整合开发案例

SSM整合开发案例

2022-08-09 07:24:00 哈希疯

SSM整合开发

SSM :SpringMVC + Spring + MyBatis

SpringMVC:视图层,界面层, 负责接收请求,显示处理结果的。
Spring:业务层,管理ServiceDao,工具类对象的。
MyBatis:持久层,访问数据库的

用户发起请求 —— SpringMVC接收 —— Spring中的Service对象处理业务 —— MyBatis处理数据

SSM整合也叫做SSI(IBatis也就是MyBatis的前身),整合中有容器。

  1. 第一个容器SpringMVC容器, 管理Controller控制器对象的。

  2. 第二个容器Spring容器,管理ServiceDao,工具类对象的
    我们要做的:把使用的对象交给合适的容器创建,管理。 把Controller还有web开发的相关对象交给SpringMVC容器,这些web用的对象导在SpringMVC配置文件中

ServiceDao对象定义在Spring的配置文件中,让Spring管理这些对象。

SpringMVC容器和Spring容器是有关系的,关系已经确定好了

SpringMVC容器是Spring容器的子容器,类似java中的继承。子可以访问父的内容
在子容器中的Controller可以访问父容器中的Service对象,就可以实现Controller使用Service对象

1. 实现步骤

  1. 使用spring_db的MySQL库,表使用t_student

    CREATE DATABASE IF NOT EXISTS `spring_db` DEFAULT CHARSET utf8;
    USE `spring_db`;
    DROP TABLE IF EXISTS `t_student`;
    CREATE TABLE `t_student` (
    	`id`    INT NOT NULL AUTO_INCREMENT,
        `name`  VARCHAR(80),
        `age`   INT,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10000;
    # 插入初始数据
    INSERT into t_student(name,age) VALUES ("孙四",27),("李八",30),("赵五",24),("孙五",23),("王七",21),("赵六",29),("赵一",30),("王八",27),("吴一",27),("赵二",28),("周二",21),("周一",22),("郑六",22),("王七",22),("吴四",23),("李六",22),("郑五",22),("郑三",21),("赵六",24),("王五",24),("周八",23),("郑七",20),("郑一",30),("吴五",30),("孙一",20),("郑二",21),("王三",28),("赵一",20),("吴五",27),("王七",27);
    
  2. 新建maven web项目

    File>>Project Structure>>点击+>>选择New Module>>左侧选择Maven,右侧选择maven-archetype webapp>>点击Next>>输入项目名ch07-ssm,设置项目存放路径为..\SpringMVC\ch07-ssm>>点开Artifact Coordinates设置Groupldorg.jason>>点击Finish>>选择Dependencies选项卡>>在Module SDK处选择好JDK的版本>>点击OK

  3. 加入依赖

    配置pom.xml文件,加入SpringMVCSpringMyBatis三个框架的依赖、JacksonMySQL驱动、Druid连接池、jspservlet依赖

    <dependencies>
      <!--单元测试依赖-->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
      </dependency>
      <!--servlet依赖-->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
      </dependency>
      <!--jsp依赖-->
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2.1-b03</version>
        <scope>provided</scope>
      </dependency>
      <!--Spring依赖-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.5.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.2.5.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.5.RELEASE</version>
      </dependency>
      <!--Jackson依赖-->
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.0</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0</version>
      </dependency>
      <!--Spring整合MyBatis依赖-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
      </dependency>
      <!--MyBatis依赖-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
      </dependency>
      <!--MySQL连接驱动依赖-->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
      </dependency>
      <!--Druid连接池-->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.12</version>
      </dependency>
    </dependencies>
    

    加入资源文件扫描和编译插件

    <build>
      <resources>
        <resource>
          <directory>src/main/java</directory><!--所在目录-->
          <includes><!--所在目录下的.properties与.xml文件都会扫描到-->
            <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>
    
  4. 配置web.xml

    File>>Project Structure>>在左侧当前项目名栏目下选择Web>>在右侧Deployment Descriptors选项卡处点击->>点击Apply>>在右侧Deployment Descriptors选项卡处点击+选择1 web.xml>>选择4.0版本后点击OK>>点击Apply,再点击OK

    (1) 注册DispatcherServlet

    ​ 目的:1. 创建SpringMVC容器对象,才能创建Controller类对象

    ​ 2. 创建的是Servlet,才能接收用户的请求

    (2) 注册Spring的监听器:ContextLoaderListener

    目的:创建Spring的容器对象,才能创建Service , Dao等对象。

    (3) 注册字符集过滤器,解决post请求乱码的问题

    <?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">
        <!--1.注册DispatcherServlet-->
        <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:conf/dispatcherServlet.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>
    
        <!--2.注册Spring的监听器:ContextLoaderListener-->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:conf/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!--3.注册字符集过滤器,解决post请求乱码的问题-->
        <filter>
            <filter-name>characterEncodingFilter</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>
            <init-param>
                <param-name>forceRequestEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
            <init-param>
                <param-name>forceResponseEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    

    注:

    1. src/main目录下船舰javaresourcestest三个目录,并分别将三个目录设置为Sources RootResources RootTest Sources Root(目录上单击右键选择Mark Directory as进行设置)
    2. resources目录下创建conf目录,并在conf目录下创建dispatcherServlet.xmlapplicationContext.xml两个Spring配置文件(目录上单击右键->New->XML Configuration File->Spring Config
  5. 创建包com.jason.controllercom.jason.servicecom.jason.daocom.jason.bean

  6. SpringMVCSpringMyBatis的配置文件

    (1) SpringMVC配置文件

    <?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">
        <!--SpringMVC配置文件,声明controller和其它web相关的对象-->
    
        <!-- 1.组件扫描 -->
        <context:component-scan base-package="com.jason.controller" />
    
        <!-- 2.视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
    
        <!-- 3.注解驱动(http://www.springframework.org/schema/mvc) -->
        <mvc:annotation-driven />
        <!-- (1) 响应Ajax请求,返回json (2) 解决静态资源访问问题 -->
        <!-- 4.配置静态资源 -->
        <mvc:resources mapping="/static/**" location="/static/" />
    </beans>
    

    (2) Spring配置文件

    <?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">
    
        <!-- Spring配置文件:声明Service,Dao -->
        <!-- 1. 声明数据源,连接数据库 -->
        <context:property-placeholder location="classpath:conf/jdbc.properties" />
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
        <!-- SqlSessionFactoryBean创建sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="configLocation" value="classpath:conf/mybatis.xml" />
        </bean>
    
        <!-- 2. 声明MyBatis的扫描器,创建dao对象 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
            <property name="basePackage" value="com.jason.dao" />
        </bean>
    
        <!-- 3. 声明Service的注解@Service所在的包名位置 -->
        <context:component-scan base-package="com.jason.service" />
    
        <!-- 4. 事务配置:注解的配置,aspectj的配置 -->
    </beans>
    

    (3) 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:控制mybatis全局行为-->
        <!--设置mybatis输出日志-->
        <!--<settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>--> 
    
        <!-- 设置别名 -->
        <typeAliases>
            <!-- name:实体类所在的包名(不是实体类的包名也可以) -->
            <package name="com.jason.bean"/>
        </typeAliases>
    
        <!-- sql mapper(sql映射文件)的位置 -->
        <mappers>
            <!-- name:是包名,这个包中的所有mapper.xml一次都能加载 使用package的要求: 1. mapper文件名称和dao接口名必须完全一样,包括大小写 2. mapper文件和dao接口必须在同一目录 -->
            <package name="com.jason.dao"/>
        </mappers>
    </configuration>
    

    若IDEA中的New没有MyBatis Config配置文件的创建项,可自定义配置文件模板,方法如下:

    File>>Settings>>Editor>>FIle and Code Templates>>+>>在左侧Name输入框中输入MyBatis ConfigExtension输入框中输入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:控制mybatis全局行为-->
     <settings>
         <!--设置mybatis输出日志-->
         <setting name="logImpl" value="STDOUT_LOGGING" />
     </settings>
    
     <!--设置别名-->
     <typeAliases>
         <!--name:实体类所在的包名 -->
         <package name="实体类的包名"/>
     </typeAliases> 
    
     <!-- sql mapper(sql映射文件)的位置-->
     <mappers>
         <!-- name:是包名,这个包中的所有mapper.xml一次都能加载 -->
         <package name="mapper文件所在的包名"/>
     </mappers>
    </configuration>
    

    添加MyBatis Mapper配置文件模板方法同上

    (4) 数据库的属性配置文件

    ​ 在conf目录下创建jdbc.properties数据库连接配置文件

    jdbc.url=jdbc:mysql://localhost:3306/spring_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.username=root
    jdbc.password=root
    
  7. 写代码,dao接口和mapper文件、service和实现类、controller和实体类

    (1)创建持久层处理数据

    ​ 创建接口StudentDao和对应的mapper文件StudentDao.xml

    package com.jason.dao;
    
    public interface StudentDao {
          
        Integer recordSize();
        Integer delStudent(Integer id);
        Integer alterStudent(Student stu);
        Integer insertStudent(Student student);
        Student findOneOfStudent(Integer id);
        List<Student> selectStudent(MessageModel page);
    }
    
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.jason.dao.StudentDao">
        <!-- 查询学生人数 -->
        <select id="recordSize" resultType="Integer">
            SELECT COUNT(*) FROM t_student
        </select>
        <!-- 分页查询所有学生 -->
        <select id="selectStudent" resultType="Student">
            SELECT id,name,age FROM t_student ORDER BY id DESC LIMIT #{start},#{size}
        </select>
        <!-- 注册学生 -->
        <insert id="insertStudent" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
            INSERT INTO t_student(name,age) VALUES (#{name}, #{age})
        </insert>
        <!-- 查找单个学生 -->
        <select id="findOneOfStudent" resultType="Student">
            SELECT id,name,age FROM t_student WHERE id = #{id}
        </select>
        <!-- 删除学生 -->
        <delete id="delStudent">
            DELETE FROM t_student WHERE id = #{id}
        </delete>
        <!-- 修改学生 -->
        <update id="alterStudent">
            UPDATE t_student SET name = #{name}, age = #{age} WHERE id = #{id}
        </update>
    </mapper>
    

    (2)创建业务层接口处理业务逻辑

    ​ 创建StudentServiceStudentServiceImpl

    package com.jason.service;
    
    public interface StudentService {
          
        Integer dataSize();
        Integer delStudent(Integer id);
        Integer addStudent(Student student);
        Student findOneOfStudent(Integer id);
        Integer alterStudent(Student student);
        List<Student> findStudent(MessageModel page);
    }
    
    package com.jason.service.impl;
    
    @Service
    public class StudentServiceImpl implements StudentService {
          
        @Autowired
        private StudentDao studentDao;
    
        @Override
        public Integer addStudent(Student student) {
          
            try {
          
                return studentDao.insertStudent(student) > 0 ? 1 : null;
            }catch (Exception e) {
          
                return null;
            }
        }
    
        @Override
        public Integer dataSize() {
          
            try {
          
                Integer num = studentDao.recordSize();
                return num > 0 ? num : null;
            }catch (Exception e) {
          
                return null;
            }
        }
    
        @Override
        public List<Student> findStudent(MessageModel page) {
          
            try {
          
                return studentDao.selectStudent(page);
            }catch (Exception e) {
          
                return null;
            }
        }
    
        @Override
        public Integer delStudent(Integer id) {
          
            try {
          
                return studentDao.delStudent(id) > 0 ? 1 : null;
            }catch (Exception e) {
          
                return null;
            }
        }
    
        @Override
        public Student findOneOfStudent(Integer id) {
          
            try {
          
                return studentDao.findOneOfStudent(id);
            }catch (Exception e) {
          
                return null;
            }
        }
    
        @Override
        public Integer alterStudent(Student student) {
          
            try {
          
                return studentDao.alterStudent(student) > 0 ? 1 : null;
            }catch (Exception e) {
          
                return null;
            }
        }
    }
    

    (3)创建视图层的处理器

    ​ 创建StudentController处理器

    package com.jason.controller;
    
    @Controller
    @RequestMapping("/student") // 学生模块
    public class StudentController {
          
        @Autowired
        private StudentService service;
    
        // 注册
        @ResponseBody
        @RequestMapping("/addStudent")
        public Integer addStudent(Student student) {
          
            return service.addStudent(student) != null ? student.getId() : null;
        }
    
        // 浏览
        @ResponseBody
        @RequestMapping("/queryStudent")
        public MessageModel queryStudent(MessageModel msg) {
          
            if (msg == null || msg.getStart() == null
                    || msg.getSize() == null) {
          
                msg = new MessageModel();
            }
            // 获取记录条数
            msg.setLength(service.dataSize());
            // 将结果集保存到消息模型
            msg.setObject(service.findStudent(msg));
            return msg;
        }
    
        // 删除
        @ResponseBody
        @RequestMapping("/deleteStudent")
        public Integer deleteStudent(Integer id) {
          
            return service.delStudent(id);
        }
    
        // 修改
        @ResponseBody
        @RequestMapping("/updateStudent")
        public Integer updateStudent(Student student) {
          
            return service.alterStudent(student);
        }
    }
    
  8. jsp页面

    (1)src/main/webapp/index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%
        String basePath = request. getScheme() + "://" +
                request.getServerName() + ":" + request. getServerPort() +
                request.getContextPath() + "/" ;
    %>
    <html>
    <head>
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="static/css/jquery-confirm.css">
        <style type="text/css">
            #message>div:nth-child(2) {
                position: fixed;
                z-index: 999;
                left: 50%;
                top: 20%;
                transform: translate(-50%,-20%);
            }
        </style>
        <base href="<%=basePath%>">
        <title>SSM整合框架</title>
    </head>
    <body>
    <ul id="myTab" class="nav nav-tabs">
        <li class="active"><a href="#home" data-toggle="tab">主页</a></li>
        <li><a href="#list" data-toggle="tab" οnclick="addStudent()">注册学生</a></li>
        <li><a href="#list" data-toggle="tab" οnclick="studentList(0)">学生列表</a></li>
    </ul>
    <div id="TabContent" class="tab-content">
    
        <%-- 主页 --%>
        <div class="tab-pane fade in active" id="home">
            <img src="static/images/ssm.jpg" alt="SMM整合框架">
            <h4>流程图</h4>
            <img src="static/images/lct.jpg" alt="SMM框架流程图">
        </div>
    
        <%-- 学生列表 --%>
        <div class="tab-pane fade col-md-12" id="list">
            <br/>
            <div class="m-5">
                <table class="table table-condensed table-hover">
                    <thead><th width="10%">序号</th><th>学号</th><th>姓名</th><th>年龄</th><th width="20%">操作</th></thead>
                    <tbody id="info"></tbody>
                </table>
            </div>
            <div class="text-center">
                <ul id="page-content" class="pagination"></ul>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="static/js/jquery-confirm.js"></script>
    
    <%-- 业务逻辑 --%>
    <script type="text/javascript" src="static/js/studentAdmin.js"></script>
    
    </body>
    </html>
    

    (2)src/main/webapp/static/js/studentAdmin.js

    let now_page,total_page,start;
    
    // 表单数据
    function formContent(id,name,age) {
          
        return '' +
            '<hr>' +
            '<form>' +
            '<input type="hidden" id="id" value="' + id + '">' +
            '<div class="form-group text-nowrap">' +
            '<label for="name">姓名&ensp;&ensp;</label>' +
            '<input style="display: inline-block; width: 80%" type="text" class="form-control" id="name" placeholder="请输入姓名" autocomplete="off" value="' + name + '">' +
            '</div>' +
            '<div class="form-group">' +
            '<label for="age">年龄&ensp;&ensp;</label>' +
            '<input style="display: inline-block; width: 80%" type="text" class="form-control" id="age" placeholder="请输入年龄" autocomplete="off" value="' + age + '">' +
            '</div>' +
            '</form>';
    }
    
    // 列表单行数据
    function tableTrData(num,id,name,age) {
          
        return '' +
            '<tr>' +
            '<td>' + num + '</td>' +
            '<td>' + id + '</td>' +
            '<td>' + name + '</td>' +
            '<td>' + age + '</td>' +
            '<td>' +
            '<button οnclick="delStudent(this)" class="btn btn-danger" title="删除">' +
            '<span class="glyphicon glyphicon-trash"></span>' +
            '</button>&ensp;&ensp;' +
            '<button οnclick="alterStudent(this)" class="btn btn-info" title="修改">' +
            '<span class="glyphicon glyphicon-pencil"></span>' +
            '</button>' +
            '</td>' +
            '</tr>';
    }
    
    // 提示框
    function messageBox(mode,content) {
          
        let msgBox,data = [
            ['red'   ,'错误','remove'],
            ['blue'  ,'信息','info'],
            ['green' ,'成功','ok'],
            ['orange','警告','warning'],
            ['purple','提示','exclamation'],
            ['dark'  ,'帮助','question']];
        data.forEach((list,i) => {
          
            if (mode === i || mode === list[0]) {
          
                msgBox = $.dialog({
          
                    icon    : 'glyphicon glyphicon-' + list[2] + '-sign',
                    type    : list[0],
                    title   : list[1],
                    content : content
                });
            }
        });
        setTimeout(function(){
          msgBox.close();},800);
    }
    
    // 选择列表当前行指定列
    function selectTdVal(obj,n) {
          
        return $(obj).parent().parent().children("td:nth-child("+n+")");
    }
    
    // 注册学生
    function addStudent() {
          
        $.confirm({
          
            icon   : 'glyphicon glyphicon-user',
            type   : 'blue',
            title: "注册学生",
            content: formContent('','',''),
            buttons: {
          
                cancel: {
          
                    text: "取消",
                    keys: ['esc'],
                    btnClass: 'btn-primary',
                    action: function () {
          }
                },
                formSubmit: {
          
                    text: '提交',
                    btnClass: 'btn-blue',
                    keys: ['enter'],
                    action: function () {
          
                        let name = this.$content.find('#name').val();
                        let age = this.$content.find('#age').val();
                        if (!name) {
          
                            messageBox(0, "姓名不能为空!");
                            return false;
                        } else if (name.length > 25) {
          
                            messageBox(0, "姓名不能超过25个字符!");
                            return false;
                        }
                        $.ajax({
          
                            url: "student/addStudent",
                            type: "post",
                            data: {
          name: name, age: age},
                            dataType: "json",
                            success: function (id) {
          
                                $("#info").html("").append(tableTrData(1,id,name,age));
                                messageBox(2, "注册成功!");
                            },
                            error: function () {
          
                                messageBox(0, "注册失败!");
                            }
                        });
                    }
                }
            }
        });
    }
    
    // 学生列表
    function studentList(n) {
          
        $.ajax({
          
            url: "student/queryStudent",
            type: "get",
            data: {
          
                start: (n - 1 < 0 ? 0 : n - 1) * 10,
                size: 10
            },
            dataType: "json",
            success: function (data) {
          
                start = data.start;
                now_page = (data.start + data.size) / data.size;
                total_page = Math.floor(data.length / data.size);
    
                $("#info").html("");
                $.each(data.object,function (i,n) {
          
                    let num = i + 1 + (now_page-1) * 10;
                    $("#info").append(tableTrData(num,n.id,n.name,n.age));
                });
                pageControl();
            }
        })
    }
    
    // 页码显示控制
    function pageControl() {
          
        let start,end;
        if (now_page <= 3) {
          
            start = now_page === 0 ? 0 : 1;
            end = total_page < 5 ? total_page : 5;
        } else {
          
            start = ((now_page + 2) > total_page ? total_page - 2 : now_page)-2;
            end = (now_page + 2) > total_page ? total_page : (now_page + 2);
        }
        let last = now_page - 1 < 1 ? 1 : now_page - 1;
        let next = now_page + 1 > total_page ? total_page : now_page + 1;
    
        // 页面项单条数据
        function pageContent(page,val) {
          
            return '' +
                '<li>' +
                '<a href="javascript:studentList(' + page + ');">' + val + '</a>' +
                '</li>';
        }
    
        // 添加首页和上一页按钮
        $("#page-content").html("").append(pageContent(1,'首页')).append(pageContent(last,'&laquo;'));
        // 添加页码按钮
        for (let i = start; i <= end; i++) {
          
            $("#page-content").append(pageContent(i,i));
            if (now_page === i) {
          
                $("#page-content>li:last").addClass("active");
            }
        }
        // 添加下一页和尾页按钮
        $("#page-content").append(pageContent(next,'&raquo;')).append(pageContent(total_page,'尾页'));
    
        $("#page-content").attr("title","共" + total_page + "页");
    
        // 样式控制
        if(now_page === 1) {
          
            $("#page-content>li:nth-child(-n+2)").addClass("disabled").children('a').removeAttr('href');
        } else if(now_page === total_page) {
          
            $("#page-content>li:nth-last-child(-n+2)").addClass("disabled").children('a').removeAttr('href');
        }else if(now_page === 0) {
          
            $("#page-content>li:nth-child(n)").addClass("disabled").children('a').removeAttr('href');
        }
    }
    
    // 删除学生
    function delStudent(obj) {
          
        let content = '确定要删除【<span style="color:red;font-weight:bold;">' + selectTdVal(obj,3).html() + '</span>】的记录?';
        $.confirm({
          
            icon  : 'glyphicon glyphicon-warning-sign',
            type  : 'orange',
            title : '提示',
            autoClose: 'close|2000',
            content : content,
            buttons : {
          
                close  : {
          
                    text: "取消",
                    keys: ['esc'],
                    btnClass: 'btn-primary',
                    action: function () {
          }
                },
                ok : {
          
                    text: '确认',
                    keys: ['enter'],
                    btnClass: 'btn-blue',
                    action: function () {
          
                        $.ajax({
          
                            url  : "student/deleteStudent",
                            type : "post",
                            data : {
           id : selectTdVal(obj,2).html() },
                            dataType : "json",
                            success : function () {
          
                                $(obj).parent().parent().remove();
                                messageBox(2, "删除成功!");
                            },
                            error   : function () {
          messageBox(0, "删除失败!");}
                        });
                    }
                }
            }
        });
    }
    
    // 修改学生
    function alterStudent(obj) {
          
        let id = selectTdVal(obj,2).html();
        let name = selectTdVal(obj,3).html();
        let age = selectTdVal(obj,4).html();
        $.confirm({
          
            icon   : 'glyphicon glyphicon-user',
            type   : 'blue',
            title  : '修改信息',
            content: formContent(id,name,age),
            buttons: {
          
                cancel: {
          
                    text: "取消",
                    keys: ['esc'],
                    btnClass: 'btn-primary',
                    action:function () {
          }
                },
                formSubmit: {
          
                    text: '提交',
                    keys: ['enter'],
                    btnClass: 'btn-blue',
                    action: function () {
          
                        let name2 = this.$content.find('#name').val();
                        let age2 = this.$content.find('#age').val();
                        if(!name2){
          
                            messageBox(0,"姓名不能为空!");
                            return false;
                        } else if(name2.length > 25){
          
                            messageBox(0,"姓名不能超过25个字符!");
                            return false;
                        }else if(name === name2 && age === age2) {
          
                            messageBox(0,"未修改任何数据!");
                            return false;
                        }
                        $.ajax({
          
                            url      : "student/updateStudent",
                            type     : "post",
                            data     : {
          id:id,name:name2,age:age2},
                            dataType : "json",
                            success  : function () {
          
                                selectTdVal(obj,3).html(name2);
                                selectTdVal(obj,4).html(age2);
                                messageBox(2, "修改成功!");
                            },
                            error    : function () {
          
                                messageBox(0, "修改失败!");
                            }
                        });
                    }
                }
            }
        });
    }
    

(3)复制图片src/main/webapp/static/images/ssm.jpgsrc/main/webapp/static/images/lct.jpg

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AxLFAaDO-1622986833036)(README.assets/image-20210605033819381.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gHUCv2Os-1622986833041)(README.assets/image-20210605033803776.png)]

(3)复制图片src/main/webapp/static/images/ssm.jpgsrc/main/webapp/static/images/lct.jpg
在这里插入图片描述
在这里插入图片描述

测试结果

主页

在这里插入图片描述

注册

在这里插入图片描述

学生列表

在这里插入图片描述

修改操作

在这里插入图片描述

原网站

版权声明
本文为[哈希疯]所创,转载请带上原文链接,感谢
https://blog.csdn.net/yu57955/article/details/117579762