教務管理系統

少侠gqk發表於2024-06-07

1 專案簡介

教務管理系統主要模組:

郵箱註冊:使用者根據郵箱傳送驗證碼註冊使用者資訊

郵箱登入:使用者根據註冊的郵箱登入

教師管理:主要包含教師的全部查詢,教師資訊的修改,新增教師資訊,刪除教師資訊,分頁查詢教師資訊

多條件查詢教師資訊(教師編號,名稱,性別,入職日期),欄位排序,匯出EXECL表,列印教師資訊

學生管理:同教師管理

傳送郵件:使用者可以給其它老師或者學生髮送郵件資訊

2 專案環境

開發工具 idea2023.3.5
jdk jdk17
maven 3.6.3
SpringBoot 3.0.2
資料庫 mysql 10.3.7-MariaDB
mybatisplus 3.5.3.1
layui 最新版本

3 環境搭建

3.1 利用Spring Initializr 快捷建立SpringBoot專案

3.2 新增pom.xml依賴

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--新增郵件依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mybatis-plus  -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

3.3 啟動主配置類

訪問http://localhost:8080 可以看到歡迎頁面

4 郵箱註冊編寫

image

匯入資料裡面的專案:layuiAdmin-master

4.1 建立資料庫表

CREATE TABLE `user` (
  `id` INT(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
  `name` VARCHAR(30) COLLATE utf8_bin DEFAULT NULL COMMENT '姓名',
  `password` VARCHAR(20) COLLATE utf8_bin NOT NULL,
  `email` VARCHAR(50) COLLATE utf8_bin DEFAULT NULL COMMENT '郵箱',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

4.2 註冊客戶端編寫

4.2.1 註冊頁面完成

注意:在頁面需要引入layui.css、jquery.min.js、layui.js

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>註冊</title>
    <!-- 請勿在專案正式環境中引用該 layui.css 地址 -->
    <link href="../../layui/css/layui.css" rel="stylesheet">
    <script src="../../jquery.min.js"></script>
</head>
<body>
<style>
    .demo-reg-container{width: 320px; margin: 21px auto 0;}
    .demo-reg-other .layui-icon{position: relative; display: inline-block; margin: 0 2px; top: 2px; font-size: 26px;}
</style>
<form class="layui-form">
    <div class="demo-reg-container">
        <div class="layui-form-item">
            <div class="layui-row">
                <div class="layui-col-xs7">
                    <div class="layui-input-wrap">
                        <div class="layui-input-prefix">
                            <i class="layui-icon layui-icon-email"></i>
                        </div>
                        <input type="text" name="email" value="" lay-verify="required|email" placeholder="郵箱號" lay-reqtext="請填寫郵箱" autocomplete="off" class="layui-input" id="reg-cellemail">
                    </div>
                </div>
                <div class="layui-col-xs5">
                    <div style="margin-left: 11px;">
                        <button type="button" id="code_btn" class="layui-btn layui-btn-fluid layui-btn-primary" lay-on="reg-get-vercode">獲取驗證碼</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-vercode"></i>
                </div>
                <input type="text" name="vercode" value="" lay-verify="required" placeholder="驗證碼" lay-reqtext="請填寫驗證碼" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                </div>
                <input type="password" name="password" value="" lay-verify="required" placeholder="密碼" autocomplete="off" class="layui-input" id="reg-password" lay-affix="eye">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                </div>
                <input type="password" name="confirmPassword" value="" lay-verify="required|confirmPassword" placeholder="確認密碼" autocomplete="off" class="layui-input" lay-affix="eye">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-wrap">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                </div>
                <input type="text" name="nickname" value="" lay-verify="required" placeholder="暱稱" autocomplete="off" class="layui-input" lay-affix="clear">
            </div>
        </div>
        <div class="layui-form-item">
            <input type="checkbox" name="agreement" lay-verify="required" lay-skin="primary" title="同意">
            <a href="#terms" target="_blank" style="position: relative; top: 6px; left: -15px;">
                <ins>使用者協議</ins>
            </a>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-reg">註冊</button>
        </div>
        <div class="layui-form-item demo-reg-other">
            <label>社交賬號註冊</label>
            <span style="padding: 0 21px 0 6px;">
        <a href="javascript:;"><i class="layui-icon layui-icon-login-qq" style="color: #3492ed;"></i></a>
        <a href="javascript:;"><i class="layui-icon layui-icon-login-wechat" style="color: #4daf29;"></i></a>
        <a href="javascript:;"><i class="layui-icon layui-icon-login-weibo" style="color: #cf1900;"></i></a>
      </span>
            <a href="#login">登入已有帳號</a>
        </div>
    </div>
</form>
<!-- 請勿在專案正式環境中引用該 layui.js 地址 -->
<script src="../../layui/layui.js"></script>

</body>
</html>

4.2.2 引入layui相應模組(表單驗證)

layui.use(function(){
        var $ = layui.$;//jquery模組
        var form = layui.form;//表單模組
        var layer = layui.layer;//彈出層
        var util = layui.util;//工具模組
 });

表單驗證

// 自定義驗證規則
        form.verify({
            // 確認密碼
            confirmPassword: function(value, item){
                var passwordValue = $('#reg-password').val();
                if(value !== passwordValue){
                    return '兩次密碼輸入不一致';
                }
            }
        });

4.2.3 郵件傳送

客戶端:

     // 普通事件
        util.on('lay-on', {
            // 獲取驗證碼
            'reg-get-vercode': function(othis){
                var countdown = 61;
                var timer= setInterval(function (){//郵件傳送後按鈕倒數計時60S
                    countdown--;
                    $("#code_btn").text(countdown+"s");
                    $("#code_btn").attr('disabled', "true");
                    if(countdown<0){
                        clearInterval(timer);
                        $("#code_btn").text("獲取驗證碼");
                        $("#code_btn").attr('disabled', false);
                    }
                },1000)

                var isvalid = form.validate('#reg-cellemail'); // 主動觸發驗證,v2.7.0 新增
                // 驗證透過
                if(isvalid){

                    var data = {
                        name:$("#reg-cellemail").val()
                    }
                    $.post("../../sendEmail2",data,function (data){//此處傳送郵件傳送的後臺介面

                    })
                }
            }
        });

後臺application.yml配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db9
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  mail:
    host: smtp.qq.com #郵件伺服器地址
    port: 465 #埠號
    username: 2939608988@qq.com
    password: mokilwljwvnodchh
    default-encoding: UTF-8 #預設編碼格式
    properties:
      mail:
        debug: true #啟動debug除錯
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory #SSL連線配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:/mapper/*.xml

前提是需要開啟qq郵箱的POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務

image

然後獲取授權碼:填入到application.yml檔案的mail.password中

實體物件編寫

實體物件屬性和資料庫中表欄位保持一致

@Data
@TableName("user")
public class User implements Serializable {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
    private String password;
    private String email;
}

Mapper介面編寫

public interface UserMapper extends BaseMapper<User> {
}

在啟動類上掃描Mapper介面


@SpringBootApplication
@MapperScan("com.gqk.mapper")
public class QueryteacherApplication {

    public static void main(String[] args) {
        SpringApplication.run(QueryteacherApplication.class, args);
    }

}

util包中編寫隨機驗證碼

package com.gqk.util;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Random;
@Component
public class Code {
    //定義驗證碼內容
    char[] codeSequence = { 'a', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'i', 'J',
            'k', 'L', 'M', 'N', 'o', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'w',
            'X', 'y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    public  StringBuilder getCode(){
        //定義隨機數類
        Random r = new Random();
        StringBuilder builderCode = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            char c = codeSequence[r.nextInt(codeSequence.length)];
            builderCode.append(c);
        }
        return builderCode;
    }
}

Service郵件傳送業務編寫

@Component
public class MyMailService {
    @Autowired
    JavaMailSender javaMailSender;
    public void sendMail(String from,String to,String subject,String text){
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom(from);//傳送者
        smm.setTo(to);//收件人
        //smm.setCc(cc);//抄送人
        smm.setSubject(subject);//郵件主題
        smm.setText(text);//郵件內容
        javaMailSender.send(smm);//傳送郵件
        System.out.println("郵件傳送成功================");
    }
}

Controller編寫

package com.gqk.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gqk.entity.User;
import com.gqk.mapper.UserMapper;
import com.gqk.service.MyMailService;
import com.gqk.util.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "*")////跨域處理
public class UserController {
    @Autowired
    private Code code;
    @Autowired
    private MyMailService myMailService;
    StringBuilder strcode = null;
    @RequestMapping("/sendEmail2")
    @CrossOrigin(origins = "*")//跨域處理
    public void sendEmail2(@RequestParam("name") String name){
        strcode = code.getCode();
        String text = "【尊敬的使用者,您註冊的驗證碼為:"+strcode+" 請不要洩露您的驗證碼】";
        myMailService.sendMail("2939608988@qq.com",
                name,"註冊驗證碼",text);
    }

}

4.2.4註冊提交

傳送客戶端請求

// 提交事件
        form.on('submit(demo-reg)', function(data){
            var field = data.field; // 獲取表單欄位值
            // 是否勾選同意
            if(!field.agreement){
                layer.msg('您必須勾選同意使用者協議才能註冊');
                return false;
            }
            $.post("../../regist",field,function (msg){//傳送註冊請求
                if(msg=="success"){
                    layer.confirm("註冊成功,是否跳轉登入頁面", {
                        btn: ['確定', '關閉'] //按鈕
                    },function (){
                        window.location.href="login.html"
                    })
                }else{
                    layer.msg("驗證碼錯誤...")
                }

            })
            return false; // 阻止預設 form 跳轉
        });

服務端Controller

  @RequestMapping("/regist")
    public String regist(@RequestParam("nickname")String name,
                         @RequestParam("password") String pwd,
                         @RequestParam("email") String email,
                         @RequestParam("vercode") String vercode){
        if(strcode.toString().equals(vercode)){//校驗郵箱驗證碼
            User user = new User();
            user.setEmail(email);
            user.setName(name);
            user.setPassword(pwd);
            System.out.println(user);
            userMapper.insert(user);
            return "success";
        }else{
            return "驗證碼錯誤...";
        }
    }

5 郵箱登入

image

客戶端頁面:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>後臺登入</title>
		<link rel="stylesheet" type="text/css" href="../../static/admin/layui/css/layui.css" />
		<link rel="stylesheet" type="text/css" href="../../static/admin/css/login.css" />
		<script src="../../jquery.min.js"></script>
	</head>

	<body>
		<div class="m-login-bg">
			<div class="m-login">
				<h3>教務管理系統</h3>
				<div class="m-login-warp">
					<form class="layui-form">
						<div class="layui-form-item">
							<input type="text" name="name" required  lay-verify="required"  placeholder="郵箱名" autocomplete="off" class="layui-input">
						</div>
						<div class="layui-form-item">
							<input type="password" name="password" required lay-verify="required" placeholder="密碼" autocomplete="off" class="layui-input">
						</div>
					<!--	<div class="layui-form-item">
							<div class="layui-inline">
								<input type="text" name="verity" required lay-verify="required" placeholder="驗證碼" autocomplete="off" class="layui-input">
							</div>
							<div class="layui-inline">
								<img class="verifyImg" onclick="this.src=this.src+'?c='+Math.random();" src="../../yzm" />
							</div>
						</div>-->
						<div class="layui-form-item m-login-btn">
							<div class="layui-inline">
								<button class="layui-btn layui-btn-normal" lay-submit lay-filter="login">登入</button>
							</div>
							<div class="layui-inline">
								<button type="button" id="regist" class="layui-btn layui-btn-primary">註冊</button>
							</div>
						</div>
					</form>
				</div>
				<p class="copyright">Copyright 2023-2024 by gqk</p>
			</div>
		</div>
		<script src="../../static/admin/layui/layui.js" type="text/javascript" charset="utf-8"></script>
		<script>
			$(function (){
				$("#regist").click(function (){
					window.location.href="regist.html"
				})
			})
			layui.use(['form', 'layedit', 'laydate'], function() {
				var form = layui.form(),
					layer = layui.layer;


				//自定義驗證規則
				form.verify({
					title: function(value) {
						if(value.length < 5) {
							return '標題至少得5個字元啊';
						}
					},
					password: [/(.+){6,12}$/, '密碼必須6到12位'],
					verity: [/(.+){6}$/, '驗證碼必須是6位'],
					
				});

				
				//監聽提交
				form.on('submit(login)', function(data) {
					var field = data.field;
					console.log(field);
					$.post("../../login",field,function (msg){
						if(msg=="success"){
                            //登入成功透過URL傳遞使用者名稱稱
							window.location.href="index.html?"+field.name
						}else{
							layer.alert("使用者名稱或者密碼錯誤",{icon: 2})

						}
					})
					return false;

				});

			});
			// 設定cookie函式
		</script>
	</body>

</html>

5.1 服務端

    @RequestMapping("/login")
    @CrossOrigin(origins = "*")
    public String login(@RequestParam("name")String name,
                        @RequestParam("password") String password){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email",name).eq("password",password);

        User user = userMapper.selectOne(userQueryWrapper);
        if(user!=null){
            return "success";
        }else{
            return "error";
        }
    }

5.2 登入成功後跳轉主頁面

主頁面獲取使用者登入回顯

<script>
var url = location.href;
var num =url.indexOf("?");
var str = url.substr(num+1);
if(str.length==44){
$("#u").html("遊客登入");
$("#u").attr("data-url","")
}else{
$("#u").html("歡迎" +str);
}							 
</script>

image

6 教師管理模組

匯入資料裡面的專案:layuiAdmin-master

image

6.1 分頁查詢

點選教師資訊管理:主頁面找到下面程式碼

<a href="javascript:;" data-url="教師資訊頁面" data-id='1' data-text="教師資訊管理">
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>資訊查詢</title>
    <link href="/layui/css/layui.css" rel="stylesheet">
    <script src="../../jquery.min.js"></script>
    <script src="/layui/layui.js"></script>
</head>
<body>
<style>
    *{
        padding: 0;
        margin: 0;
    }
    .demo-login-container{width: 1000px;  }
</style>
<script type="text/html" id="toolbarDemo">
    <form class="layui-form layui-row layui-col-space16" >
        <div class="demo-login-container" >
            <div class="layui-input-wrap" style="display: inline-block;width: 200px">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                </div>
                <input type="text" name="id"  value="" placeholder="請輸入編號" class="layui-input" lay-affix="clear">
            </div>


            <div class="layui-input-wrap" style="display: inline-block;width: 200px">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                </div>
                <input type="text" name="name"  value="" placeholder="請輸入名稱" class="layui-input" lay-affix="clear">
            </div>




            <div class="layui-input-wrap" style="display: inline-block;width: 200px">
                <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-date"></i>
                </div>
                <input type="text" name="hiredate"  readonly placeholder="請選擇日期" class="layui-input demo-table-search-date">
            </div>


                <div class="layui-input-wrap" style="display: inline-block;width: 150px">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-login-qq"></i>
                    </div>
                    <select name="sex"  lay-search>
                        <option value="">請選擇性別</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>



            <button class="layui-btn " lay-submit lay-filter="demo-table-search">查詢</button>
            <button class="layui-btn " id="dropdownButton">
                操作
                <i class="layui-icon layui-icon-down layui-font-12"></i>
            </button>

        </div>

    </form>

</script>

<table class="layui-hide" id="ID-table-demo-search"></table>
</body>
<script>
    layui.use(function (){
        var table = layui.table;
        var form = layui.form;
        var laydate = layui.laydate;
        var dropdown = layui.dropdown;
        // 建立表格例項
        table.render({
            elem: '#ID-table-demo-search',
            url: '../../queryAllTeacherByPage', 
            limits:[5,10,15],
            toolbar: '#toolbarDemo',
            cols: [[
                {type: 'checkbox', title: '😊', fixed: true}, // 單選框
                {field:'id', title: '編號', sort: true, fixed: true,align:"center"},
                {field:'name', title: '老師名稱',align:"center"},
                {field:'sex', title: '老師性別',align:"center"},
                {field:'salary', title: '老師工資',sort: true,align:"center" },
                {field:'hiredate', title: '入職日期',align:"center"},
                {field:'tel', title: '聯絡方式',align:"center"},
                {field:'address', title: '家庭住址'}
            ]]
        });
        // 日期
        laydate.render({
            elem: '.demo-table-search-date'
        });
    })
</script>
</html>

查詢條件實體類物件

package com.gqk.entity;
import lombok.Data;
@Data
public class Query {
    private Integer id;
    private String name;
    private String hiredate;
    private String sex;
    private Integer page;
    private Integer limit;
}

分頁配置類編寫

package com.gqk.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration

public class PageConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

TeacherMapper編寫

public interface TeacherMapper extends BaseMapper<Teacher> {

}

控制層編寫

package com.gqk.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gqk.entity.Query;
import com.gqk.entity.Teacher;
import com.gqk.mapper.TeacherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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


@RestController
public class TeacherController {
    @Autowired
    private TeacherMapper teacherMapper;

    @RequestMapping("/queryAllTeacherByPage")
    public Map<String,Object> queryAllTeacherByPage(Query query){
        Page<Teacher> pages = new Page<>(query.getPage(), query.getLimit());
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        Long count = teacherMapper.selectCount(queryWrapper);
        teacherMapper.selectPage(pages, queryWrapper);
        List<Teacher> list = pages.getRecords();
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",list);
        return map;
    }

}

6.2 多條件分頁查詢

客戶端傳送條件查詢

<button class="layui-btn " lay-submit lay-filter="demo-table-search">查詢</button>
// 搜尋提交
        form.on('submit(demo-table-search)', function(data){
            var field = data.field; // 獲得表單欄位

            // 執行搜尋過載
            table.reload('ID-table-demo-search', {
                where:field,
                done:function (){
                    laydate.render({//解決查詢完後時間元件失效
                        elem: '.demo-table-search-date'
                    });
                }
            })

            return false; // 阻止預設 form 跳轉
        });

服務端查詢

  @RequestMapping("/queryAllTeacherByPage")
    public Map<String,Object> queryAllTeacherByPage(Query query){
        Page<Teacher> pages = new Page<>(query.getPage(), query.getLimit());
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        if(query.getId()!=null && !"".equals(query.getId())){
            queryWrapper.eq("id",query.getId());
        }
        if(query.getName()!=null && !"".equals(query.getName())){
            queryWrapper.like("name","%"+query.getName()+"%");
        }
        if(query.getSex()!=null && !"".equals(query.getSex())){
            queryWrapper.eq("sex",query.getSex());
        }
        if(query.getHiredate()!=null && !"".equals(query.getHiredate())){
            queryWrapper.eq("hiredate",query.getHiredate());
        }
        Long count = teacherMapper.selectCount(queryWrapper);
        teacherMapper.selectPage(pages, queryWrapper);
        List<Teacher> list = pages.getRecords();
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",list);
        return map;
    }

6.3 新增教師資訊

image

客戶端頁面:

table.render({
            elem: '#ID-table-demo-search',
            url: '../../queryAllTeacherByPage', 
            limits:[5,10,15],
            toolbar: '#toolbarDemo',

            cols: [[
                {type: 'checkbox', title: '😊', fixed: true}, // 單選框
                {field:'id', title: '編號', sort: true, fixed: true,align:"center"},
                {field:'name', title: '老師名稱',align:"center"},
                {field:'sex', title: '老師性別',align:"center"},
                {field:'salary', title: '老師工資',sort: true,align:"center" },
                {field:'hiredate', title: '入職日期',align:"center"},
                {field:'tel', title: '聯絡方式',align:"center"},
                {field:'address', title: '家庭住址'}
            ]],
            done:function (){
                var id = this.id;
                //下拉渲染
                dropdown.render({
                    elem: '#dropdownButton',
                    data: [{
                        id: 'add',
                        title: '新增'
                    },{
                        id: 'update',
                        title: '修改'
                    },{
                        id: 'delete',
                        title: '刪除'
                    }],
                    click:function (obj){
                        var checkStatus = table.checkStatus(id)
                        var data = checkStatus.data; // 獲取選中的資料
                        switch(obj.id){
                            case 'add':
                                layer.open({
                                    title: '新增教師',
                                    type: 2,
                                    area: ['75%','100%'],
                                    content: 'add.html',
                                    skin:"layui-layer-molv",
                                    anim:5
                                });
                                break;
                            case 'update':
                                if(data.length !== 1) return layer.msg('請選擇一行');
                                var index = layer.open({
                                    title: '修改老師資訊',
                                    type: 2,
                                    area: ['70%','85%'],
                                    content: 'update.html',
                                    skin:"layui-layer-molv",
                                    anim:5,
                                    success:function (dom,index){
                              		//因為修改的頁面是update.html存在傳值問題(不是一個頁面)
                                        var iframeWindow = window['layui-layer-iframe'+ index]
                                        iframeWindow.edite(data);
                                    }
                                });
                                break;
                            case 'delete':
                                if(data.length === 0){
                                    return layer.msg('請選擇一行');
                                }




                                var ids = [];
                                for(var i = 0;i<data.length;i++){
                                    var idd = data[i].id;
                                    ids.push(idd)
                                }
                                layer.confirm('您確定要刪除<font color="red">'+ids.length+"</font>條記錄嗎?", {icon: 3}, function(){
                                    $.ajax({
                                        type : 'post',
                                        url : "deleteTeacherByIds",
                                        dataType : 'json',
                                        contentType : 'application/json',
                                        data : JSON.stringify(ids),
                                        success : function (count) { // 返回的RequestResult的json物件
                                            if(count>0){
                                                layer.msg('刪除成功...');
                                                table.reload("ID-table-demo-search")
                                            }
                                        },
                                    });
                                }, function(){
                                    layer.msg('取消刪除',{icon: 1});
                                });
                                break;
                        }

                    }
                })
            },
            page: true,
            height: 550
        });

彈窗為新增頁面add.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>新增老師資訊</title>

    <link href="/layui/css/layui.css" rel="stylesheet">
    <script src="../../jquery.min.js"></script>
    <script src="/layui/layui.js"></script>
</head>
<style>
    *{
        padding: 0;
        margin: 0;
    }
    .container{
        width: 50%;
        margin:0 auto;
        border: 2px solid #b2b2b2;
        margin-top: 20px;

    }
</style>
<body >
    <div class="container">
        <form class="layui-form" style="margin-top: 20px">
            <div class="layui-form-item">
                <label class="layui-form-label">教師名稱:</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" lay-verify="required" placeholder="請輸入教師名稱"  class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">教師性別:</label>
                <div class="layui-input-inline">
                    <input type="radio" name="sex" value="男" title="男" >
                    <input type="radio" name="sex" value="女" title="女">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">教師工資:</label>
                <div class="layui-input-inline">
                    <input type="number" name="salary" lay-verify="required" placeholder="請輸入教師工資"  class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">入職日期:</label>
                <div class="layui-input-wrap" style="display: inline-block;width: 190px">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-date"></i>
                    </div>
                    <input type="text" name="hiredate"  readonly placeholder="請選擇日期" class="layui-input demo-table-search-date">
                </div>
            </div>

            <div class="layui-form-item" style="display: none">
                <div class="layui-inline">

                    <div class="layui-input-inline layui-input-wrap">
                        <input type="text" name="id" value="101"  autocomplete="off" lay-reqtext="請填寫手機號" lay-affix="clear" class="layui-input demo-phone">
                    </div>
                </div>
            </div>


            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">聯絡方式:</label>
                    <div class="layui-input-inline layui-input-wrap">
                        <input type="tel" name="tel" lay-verify="required|phone" autocomplete="off" lay-reqtext="請填寫手機號" lay-affix="clear" class="layui-input demo-phone">
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">家庭住址:</label>
                <div class="layui-input-block" style="width: 190px">
                    <textarea placeholder="請輸入內容" lay-verify="required" name="address" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="add-submit">立即新增</button>
                    <button type="reset" class="layui-btn layui-btn-primary">立即重置</button>
                </div>
            </div>

        </form>
    </div>
    <script>
        var index = parent.layer.getFrameIndex(window.name); // 獲取視窗索引
        layui.use(function (){
            var form = layui.form;
            var laydate = layui.laydate;
            // 日期
            laydate.render({
                elem: '.demo-table-search-date'
            });
            //提交表單資料
            form.on('submit(add-submit)', function(data){
                var field = data.field; // 獲取表單全部欄位值
                $.post("insertTeacher",field,function (data){
                    if(data==1){
                        //parent.layui.table.reload("ID-table-demo-search")
                        //重新載入父頁面中的id為ID-table-demo-search的資料表格
                        parent.layui.table.reload("ID-table-demo-search");
                        layer.msg('恭喜您新增成功', {icon: 1,time: 1000}, function(){
                            parent.layer.close(index);
                        });
                    }
                })
                return false; // 阻止預設 form 跳轉
            })


        });

    </script>
</body>
</html>

TeacherMapper編寫

public interface TeacherMapper extends BaseMapper<Teacher> {

    @Insert(" INSERT INTO teacher ( name, sex, salary, hiredate, tel, address ) VALUES" +
            " ( #{teacher.name}, #{teacher.sex}, #{teacher.salary}," +
            " #{teacher.hiredate}, #{teacher.tel}, #{teacher.address} )")
    void insertTeacher(@Param("teacher") Teacher teacher);

}

TeacherController編寫

    @RequestMapping("/insertTeacher")
    public Integer insertTeacher(Teacher teacher){
        teacherMapper.insertTeacher(teacher);
        return 1;
    }

6.4 修改教師資訊

修改教師資訊需要選擇要修改的老師,並對老師資訊進行回顯在修改表單中

image

update.html彈窗

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>修改老師資訊</title>

    <link href="/layui/css/layui.css" rel="stylesheet">
    <script src="../../jquery.min.js"></script>
    <script src="/layui/layui.js"></script>
</head>
<style>
    *{
        padding: 0;
        margin: 0;
    }
    .container{
        width: 50%;
        margin:0 auto;
        border: 2px solid #b2b2b2;
        margin-top: 20px;

    }
</style>
<body >
    <div class="container" class="layui-layer-iframe" >
        <form class="layui-form" lay-filter="demo-val-filter" style="margin-top: 20px">
            <div class="layui-form-item">
                <label class="layui-form-label">教師名稱:</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" lay-verify="required" placeholder="請輸入教師名稱"  class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">教師性別:</label>
                <div class="layui-input-inline">
                    <input type="radio" name="sex" id="man" value="男" title="男"  >
                    <input type="radio" name="sex" id="women" value="女" title="女">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">教師工資:</label>
                <div class="layui-input-inline">
                    <input type="number" name="salary" lay-verify="required" placeholder="請輸入教師工資"  class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">入職日期:</label>
                <div class="layui-input-wrap" style="display: inline-block;width: 190px">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-date"></i>
                    </div>
                    <input type="text" name="hiredate"   readonly placeholder="請選擇日期" class="layui-input demo-table-search-date">
                </div>
            </div>

            <div class="layui-form-item" style="display: none">
                <div class="layui-inline">

                    <div class="layui-input-inline layui-input-wrap">
                        <input type="text" name="id" value="101"  autocomplete="off" lay-reqtext="請填寫手機號" lay-affix="clear" class="layui-input demo-phone">
                    </div>
                </div>
            </div>


            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">聯絡方式:</label>
                    <div class="layui-input-inline layui-input-wrap">
                        <input type="tel" name="tel" lay-verify="required|phone" autocomplete="off" lay-reqtext="請填寫手機號" lay-affix="clear" class="layui-input demo-phone">
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">家庭住址:</label>
                <div class="layui-input-block" style="width: 190px">
                    <textarea placeholder="請輸入內容" lay-verify="required" name="address" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="add-submit">立即修改</button>
                    <button type="reset" class="layui-btn layui-btn-primary">立即重置</button>
                </div>
            </div>

        </form>
    </div>
    <script>
        var index = parent.layer.getFrameIndex(window.name); // 獲取視窗索引
        var edite = function (data){
            layui.use(function (){
                var form = layui.form;
                var laydate = layui.laydate;
                // 日期
                laydate.render({
                    elem: '.demo-table-search-date'
                });
                var sex = data[0].sex;
                if(sex=="男"){
                    $("#man").attr("checked","checked")
                }else{
                    $("#women").attr("checked","checked")
                }
                console.log(data)
                //給form表單賦值
                form.val("demo-val-filter",{
                        "name":data[0].name,
                        "id":data[0].id,
                        "salary":data[0].salary,
                        "hiredate":data[0].hiredate,
                        "tel":data[0].tel,
                        "address":data[0].address,
                        "sex":data[0].sex


                })
                //提交表單資料
                form.on('submit(add-submit)', function(data){
                    var field = data.field; // 獲取表單全部欄位值
                    $.post("updateTeacher",field,function (data){
                        if(data==1){
                            //parent.layui.table.reload("ID-table-demo-search")
                            //重新載入父頁面中的id為ID-table-demo-search的資料表格
                            parent.layui.table.reload("ID-table-demo-search");
                            layer.msg('恭喜您修改成功', {icon: 1,time: 1000}, function(){
                                parent.layer.close(index);
                            });
                        }
                    })
                    return false; // 阻止預設 form 跳轉
                })

            });
        }

    </script>
</body>
</html>

TeacherController編寫

@RequestMapping("/updateTeacher")
    public Integer updateTeacher(Teacher teacher){
        int i = teacherMapper.updateById(teacher);
        return i;
    }

6.5 刪除教師資訊

客戶端請求在新增模組

 @RequestMapping("/deleteTeacherByIds")
    public Integer deleteTeacherByIds(@RequestBody List<Integer> ids){
            int cout = teacherMapper.deleteBatchIds(ids);
            return cout;
    }

7 郵件傳送

image

匯入pom.xml(在環境搭建處已經全部匯入)

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

application.yml中配置相關配置

在郵件註冊中已經配置(參照郵件註冊)

傳送請求

在email-write.html中傳送

<!DOCTYPE html>
<html class="iframe-h">
	<head>
		<meta charset="UTF-8">
		<meta name="renderer" content="webkit">
  		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>網站後臺管理模版</title>
		<link rel="stylesheet" type="text/css" href="../../static/admin/layui/css/layui.css"/>
		<link rel="stylesheet" type="text/css" href="../../static/admin/css/admin.css"/>
		<script src="../../jquery.min.js"></script>
	</head>
	<body class="iframe-h">
		<div class="email-write">
		<form class="layui-form">
			<div class="layui-form-item">
					<input type="text" name="name" lay-verify="name" autocomplete="off" placeholder="請輸入收件人" class="layui-input">
			</div>
			<div class="layui-form-item">
					<input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="請輸入主題" class="layui-input">
			</div>
			<div class="layui-form-item layui-form-text">
					<textarea  class="layui-textarea layui-hide" name="content" lay-verify="content" id="LAY_demo_editor"></textarea>
			</div>
			<div class="layui-form-item">
					<button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="demo1"><i class="layui-icon">&#xe609;</i> 立即傳送</button>
					<button type="reset" class="layui-btn layui-btn-primary"><i class="layui-icon">&#x1006;</i> 放棄</button>
					<button class="layui-btn layui-btn-primary "><i class="layui-icon">&#xe642;</i> 存為草稿</button>
			</div>
		</form>
		</div>
		<script src="../../static/admin/layui/layui.js" type="text/javascript" charset="utf-8"></script>
		<script>
			var index = parent.layer.getFrameIndex(window.name); // 獲取視窗索引
			layui.use(['form', 'layedit', 'laydate'], function(){
			  var form = layui.form()
			  ,layer = layui.layer
			  ,layedit = layui.layedit
			  ,laydate = layui.laydate;
			  
			  //建立一個編輯器
			  var editIndex = layedit.build('LAY_demo_editor');
			  
			  //監聽提交
			  form.on('submit(demo1)', function(data){
				  var mail = {
					  name:data.field.name,
					  title:data.field.title,
					  text:layedit.getContent(editIndex)
				  }
				  $.ajax({
					  type : 'post',
					  url : "../../sendEmail",
					  data : mail,
					  success : function (msg) { // 返回的RequestResult的json物件
						  layer.msg(msg, {icon: 1,time: 1000}, function(){
							  parent.layer.close(index);
						  });
					  },
				  });
			    return false;
			  });
			});
		</script>
</body>
</html>

服務端程式碼

  @RequestMapping("/sendEmail")
    public String sendE0mail(@RequestParam("name") String name,
                            @RequestParam("title") String title,
                            @RequestParam("text") String text){
        myMailService.sendMail("2939608988@qq.com",
                name,title,text);
        return "傳送成功...";

    }

革命還未成功,同志仍需努力;我們後期擁抱Vue+ElementUI

相關文章