简单的后台管理系统demo(基于Spring Boot)

前言

工程实践2和期末考试终于结束了,有空来写一下快速打通前后端的一个demo。其实是基于工程实践2项目的基础上进行优化和阉割的,因为原项目相较于即将写的这个demo大不少了。感兴趣可以到这里查看原项目,以及本文分享的新demo
本文会将一些主要文件展示出来,不会展示完所有文件。
因为项目中用到的文件相对来说比较多,全部在本文中写出来会导致篇幅会十分巨大,所以推荐先去下载项目源代码,然后配合本文食用。

实现的功能

实现登录功能、页面自动显示查询到的信息、运营账号的增删查改,多条件查询(mybatis动态查询)

正文

系统架构草图

项目结构

 
红框中的文件大家如果能大概搞明白,本文的目的就达到了。

IDEA新建项目

这里没演示maven的设置,不知道怎么设置的去查一下




mydemo建库建表.sql

点击查看详细内容
DROP DATABASE
IF EXISTS MyDemo;	-- 如果存在数据库MyDemo,那么就删除它

CREATE DATABASE MyDemo;	-- 创建数据库MyDemo

USE MyDemo;	-- 使用数据库MyDemo

DROP TABLE
IF EXISTS OAT;	-- 如果存在表OAT,那么就删除它

-- 创建运营账号表(OperatingAccountTable)
CREATE TABLE OAT (
	-- 01_用户名_主键
	username NVARCHAR (20) NOT NULL,
	-- 02_用户编号_唯一,格式OAxxx,OA代表运营账号,xxx为具体编号
	userid VARCHAR (10) NOT NULL,
	-- 03_密码
	password VARCHAR (20) NOT NULL,
	-- 04_性别,M为男性,F为女性
	sex VARCHAR (1) NOT NULL,
	-- 05_账号状态,0为禁用,1为启用,默认启用
	oastatus INT NOT NULL DEFAULT 1,
	PRIMARY KEY (username),
	UNIQUE KEY (userid)
) ENGINE = INNODB DEFAULT CHARSET = utf8;

-- 以下为测试数据
-- 运营账号
INSERT INTO OAT
VALUES(
	'lisi',		-- 01_用户名_主键
	'OA0',		-- 02_用户编号_唯一,格式OAxxx,OA代表运营账号,xxx为具体编号
	'lisi',		-- 03_密码
	'M',		-- 04_性别,M为男性,F为女性
	1			-- 05_账号状态,0为禁用,1为启用,默认启用
);
INSERT INTO OAT
VALUES(
	'test',
	'OA128',
	'test',
	'F',
	0
);
INSERT INTO OAT
VALUES(
	'hexin',
	'OA200',
	'hexin',
	'F',
	1
);

INSERT INTO OAT
VALUES(
	'lapulande',
	'OA11',
	'lapulande',
	'M',
	0
);
INSERT INTO OAT
VALUES(
	'935478677',
	'OA205',
	'935478677',
	'M',
	1
);
INSERT INTO OAT
VALUES(
	'liuli',
	'OA300',
	'liuli',
	'F',
	0
);

pom.xml

点击查看详细内容
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <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>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

这个文件里有些地方是需要修改才能用的,主要是第6、7行,这里是你数据库的账号密码。其他地方一般不用改。

点击查看详细内容
# 设置Web端口号
server.port=8080
# 设置Web上下文路径
server.servlet.context-path=/mydemo
# 设置SpringBoot默认的HikariDataSource数据源
spring.datasource.username=root
spring.datasource.password=root
# MySQL高版本(8.0及以上),推荐使用如下com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydemo?allowPublicKeyRetrieval=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
mybatis.type-aliases-package=com.example.demo.bean
mybatis.mapper-locations=classpath*:mapper/*.xml
# 控制台输出SQL语句
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 是否启用热部署(项目有修改时,自动重启)
spring.devtools.restart.enabled=false

GetAppProperties.java

点击查看详细内容
package com.example.demo.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GetAppProperties {
    /*获取配置文件application.properties中的端口号port*/
    @Bean
    public String port(@Value("${server.port}") String port) {
        return port;
    }

    /*获取配置文件application.properties中的上下文路径path*/
    @Bean
    public String path(@Value("${server.servlet.context-path}") String path) {
        return path;
    }
}

OperatingAccount.java

点击查看详细内容
package com.example.demo.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@ConfigurationProperties(prefix = "oa")
public class OperatingAccount {
    private String username; // 01_用户名_主键
    private String userid; // 02_用户编号_唯一,格式OAxxx,OA代表运营账号,xxx为具体编号
    private String password; // 03_密码
    private String sex; // 04_性别,M为男性,F为女性
    private Integer astatus = 1; // 05_账号状态,0为禁用,1为启用,默认启用
}

LoginFilter.java

点击查看详细内容
package com.example.demo.controller;

import com.example.demo.bean.OperatingAccount;
import com.example.demo.services.OperatingAccountServices;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebFilter(filterName = "LoginFilter",
    urlPatterns = "*.html", /*通配符(*)表示对所有的web资源进行拦截*/
    initParams = {
        @WebInitParam(name = "charset", value = "utf-8")    /*这里可以放一些初始化的参数*/
    })

public class LoginFilter implements Filter {
    @Resource
    private OperatingAccountServices operatingAccountServices;

    private String filterName;
    private String charset;

    @Override
    public void init(FilterConfig config) {
        /*初始化方法  接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
        filterName = config.getFilterName();
        charset = config.getInitParameter("charset");
        System.out.println("过滤器初始化:" + filterName);
        System.out.println("字符集编码:" + charset);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁:" + filterName);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws ServletException, IOException {
        /*过滤方法 主要是对request和response进行一些处理,然后交给下一个过滤器或Servlet处理*/
        req.setCharacterEncoding(charset);
        resp.setCharacterEncoding(charset);

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String url = request.getRequestURI();
        System.out.println("请求的url:" + url);

        /*处理请求页面*/
        int idx = url.lastIndexOf("/");
        String endWith = url.substring(idx + 1);

        /*判断请求页面*/
        if (!endWith.equals("login.html")) {
            System.out.println("不是登录页面,进行拦截处理");
            if (!isLogin(request)) {
                System.out.println("未登录或者账号密码错误,跳转到登录界面");
                response.setContentType("text/html; charset=UTF-8"); // 转码
                PrintWriter out = response.getWriter();
                out.flush();
                out.println("<script>");
                out.println("alert('未登录!');");
                out.println("window.location.href='login.html';");
                out.println("</script>");
                out.close();
            } else {
                System.out.println("已登录");
                chain.doFilter(req, resp);
            }
        } else {
            System.out.println("是登录页面,不进行拦截处理");
            chain.doFilter(req, resp);
        }
    }

    private boolean isLogin(HttpServletRequest request) {
        String username = "";
        String password = "";

        Cookie[] cookies = request.getCookies();    // 获取一个cookies数据,方便后续操作
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) { // 遍历cookies,寻找指定内容
                if (cookie.getName().equals("username")) {
                    username = cookie.getValue();
                } else if (cookie.getName().equals("password")) {
                    password = cookie.getValue();
                }
            }
        }

        // 通过匹配cookie中的username和password,来判断是否登录过
        if (username.equals("") || password.equals("")) {
            return false;
        } else {
            OperatingAccount oa = new OperatingAccount();
            oa.setUsername(username);
            Map<String, Object> map = this.operatingAccountServices.getOperatingAccountByUsername(oa);
            List<OperatingAccount> list = (List<OperatingAccount>) map.get("list");
            OperatingAccount o = list.get(0);
            if (username.equals(o.getUsername())) { // 账号正确
                if (password.equals(o.getPassword())) { // 密码正确
                    return true;    // 返回true,代表已登录
                }
            }
            return false;   // 账号不存在或者密码错误,则认为未登录
        }
    }
}

OperatingAccountController.java

点击查看详细内容
package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.bean.OperatingAccount;
import com.example.demo.services.OperatingAccountServices;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class OperatingAccountController {
    @Resource
    private OperatingAccountServices operatingAccountservices;

    // 01_获取所有账号信息
    @RequestMapping("/getAllAccounts")
    public Map<String, Object> getAllAccounts() {
        return this.operatingAccountservices.getAllAccounts();
    }

    // 02_按照用户编号获取账号信息
    @RequestMapping("/getOperatingAccountByUserid")
    public Map<String, Object> getOperatingAccountByid(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String userid = hashMap.get("userid").toString();
        OperatingAccount oa = new OperatingAccount();
        oa.setUserid(userid);
        return this.operatingAccountservices.getOperatingAccountByUserid(oa);
    }

    // 03_新增账号
    @RequestMapping("/addOperationalAccount")
    public Map<String, Object> addOperationalAccount(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String str_maxid = operatingAccountservices.getMaxUserid();
        int int_maxid = Integer.parseInt(str_maxid.substring(2));
        String userid = "OA" + (int_maxid + 1);
        String username = hashMap.get("username").toString();
        String password = "123456";
        String sex = hashMap.get("sex").toString();
        Integer astatus = 1;
        OperatingAccount oa = new OperatingAccount();
        oa.setUsername(username);
        oa.setUserid(userid);
        oa.setPassword(password);
        oa.setSex(sex);
        oa.setAstatus(astatus);
        Integer lines = operatingAccountservices.addOperationalAccount(oa);
        if (lines > 0) {
            List<OperatingAccount> list = Arrays.asList(oa);
            Map<String, Object> map = new HashMap<>();
            map.put("code", "0");
            map.put("list", list);
            map.put("count", list.size());
            map.put("message", "查询信息成功!");
            System.out.println(map);
            return map;
        } else {
            return null;
        }
    }

    // 04_删除账号
    @RequestMapping("/deleteOperationalAccountByUserid")
    public Integer deleteOperationalAccountByUserid(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String userid = hashMap.get("userid").toString();
        OperatingAccount oa = new OperatingAccount();
        oa.setUserid(userid);
        return this.operatingAccountservices.deleteOperationalAccountByUserid(oa);
    }

    // 05_启用/禁用账号
    @RequestMapping("/updateOperationalAccountStatusByUserid")
    public Integer updateOperationalAccountStatusByruserID(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String userid = hashMap.get("userid").toString();
        Integer astatus = Integer.parseInt(hashMap.get("astatus").toString());
        OperatingAccount oa = new OperatingAccount();
        oa.setUserid(userid);
        oa.setAstatus(astatus);
        return this.operatingAccountservices.updateOperationalAccountStatusByUserid(oa);
    }

    // 06_按照用户编号重置账号密码
    @RequestMapping("/resetOperationalAccountPasswordByUserid")
    public Integer resetOperationalAccountPasswordByUserid(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String userid = hashMap.get("userid").toString();
        OperatingAccount oa = new OperatingAccount();
        oa.setUserid(userid);
        return this.operatingAccountservices.resetOperationalAccountPasswordByUserid(oa);
    }

    // 07_按照用户名更新账号信息
    @RequestMapping("/updateOperationalAccountByUsername")
    public Integer updateOperationalAccountByusername(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String username = hashMap.get("username").toString();
        String sex = hashMap.get("sex").toString();
        OperatingAccount oa = new OperatingAccount();
        oa.setUsername(username);
        oa.setSex(sex);
        return this.operatingAccountservices.updateOperationalAccountByUsername(oa);
    }

    // 08_多条件查询
    @RequestMapping("/getOperationalAccountByMultipleConditions")
    public Map<String, Object> getOperationalAccountByMultipleConditions(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String username = hashMap.get("username").toString();
        String userid = hashMap.get("userid").toString();
        String sex = hashMap.get("sex").toString();
        switch (sex) {
            case "2":
                sex = "('M', 'F')";
                break;
            case "1":
                sex = "('M')";
                break;
            case "0":
                sex = "('F')";
                break;
        }
        Integer astatus = Integer.parseInt(hashMap.get("astatus").toString());
        if (astatus == 2) {
            astatus = null;
        }
        OperatingAccount oa = new OperatingAccount();
        oa.setUsername(username);
        oa.setUserid(userid);
        oa.setSex(sex);
        oa.setAstatus(astatus);
        return this.operatingAccountservices.getOperationalAccountByMultipleConditions(oa);
    }
}

OperatingAccountLogin.java

点击查看详细内容
package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.bean.OperatingAccount;
import com.example.demo.services.OperatingAccountServices;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class OperatingAccountLogin {
    @Resource
    private OperatingAccountServices operatingAccountServices;

    // 判断是否存在该账号
    @RequestMapping("/hasaccount")
    @ResponseBody
    public boolean hasAccount(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        OperatingAccount operatingAccount = new OperatingAccount();
        String username = hashMap.get("username").toString();
        operatingAccount.setUsername(username);
        Map<String, Object> map =
            this.operatingAccountServices.getOperatingAccountByUsername(operatingAccount);
        if (map.get("code") == "0") {
            return true;
        }
        return false;
    }

    // 检查该账号账号密码是否正确
    @RequestMapping("/checkaccount")
    @ResponseBody
    public int checkAccount(@RequestBody String data) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String username = hashMap.get("username").toString();
        String password = hashMap.get("password").toString();
        OperatingAccount operatingAccount = new OperatingAccount();
        operatingAccount.setUsername(username);
        Map<String, Object> map =
            this.operatingAccountServices.getOperatingAccountByUsername(operatingAccount);
        int res = 2;
        List<OperatingAccount> list = (List<OperatingAccount>) map.get("list");
        OperatingAccount o = list.get(0);

        if (username.equals(o.getUsername())) {  // 账号正确
            if (password.equals(o.getPassword())) { // 密码正确
                if (o.getAstatus() == 1) { // 账号启用
                    res = 1;
                } else { // 账号禁用
                    res = 0;
                }
            }
        }
        return res;
    }

    // 登录
    @RequestMapping("/login")
    @ResponseBody
    public int login(
        @RequestBody String data, HttpServletRequest request, HttpServletResponse response) {
        HashMap hashMap = JSON.parseObject(data, HashMap.class);
        System.out.println(hashMap);
        String username = hashMap.get("username").toString();
        String password = hashMap.get("password").toString();
        OperatingAccount operatingAccount = new OperatingAccount();
        operatingAccount.setUsername(username);
        Map<String, Object> map = this.operatingAccountServices.getOperatingAccountByUsername(operatingAccount);
        List<OperatingAccount> list = (List<OperatingAccount>) map.get("list");
        OperatingAccount o = list.get(0);
        int status = o.getAstatus();    //获取账号状态
        if (username.equals(o.getUsername())) { // 账号正确
            if (password.equals(o.getPassword())) { // 密码正确
                if (status == 1) {
                    // 创建cookie并将成功登录的用户保存在里面
                    Cookie cookie_username = new Cookie("username", username);
                    Cookie cookie_password = new Cookie("password", password);
                    cookie_username.setMaxAge(120); // 设置两分钟有效
                    cookie_password.setMaxAge(120);
                    response.addCookie(cookie_username); // 服务器返回给浏览器cookie以便下次判断
                    response.addCookie(cookie_password);
                }
            }
        }
        // 前端未处理返回值为2的情况
        return (status == 0 || status == 1) ? status : 2;
    }

    // 获取登录用户
    @RequestMapping("/getloginuser")
    @ResponseBody
    public Map<String, Object> getloginuser(
        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        String username = "";
        Cookie[] cookies = request.getCookies();    // 获取一个cookies数据,方便后续操作
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) { // 遍历cookies,寻找指定内容
                if (cookie.getName().equals("username")) {
                    username = cookie.getValue();
                }
            }
        }
        map.put("login_username", username);
        return map;
    }

    // 退出
    @RequestMapping("/logout")
    @ResponseBody
    public Integer logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();    // 获取一个cookies数据,方便后续操作
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) { // 遍历cookies,寻找指定内容
                if (cookie.getName().equals("username") || cookie.getName().equals("password")) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
        return 0;
    }
}

OperatingAccountDao.java

点击查看详细内容
package com.example.demo.dao;

import com.example.demo.bean.OperatingAccount;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface OperatingAccountDao {
    // 获取所有账号信息,按ID从小到大排序
    @Select("select * from oat order by substr(userID,3)+0 asc")
    List<OperatingAccount> getAllAccounts();

    // 通过用户名获取账号信息
    @Select("select * from oat where username=#{username}")
    List<OperatingAccount> getOperatingAccountByUsername(OperatingAccount oa);

    //通过用户编号获取账号信息
    @Select("select * from oat where userid=#{userid}")
    List<OperatingAccount> getOperatingAccountByUserid(OperatingAccount oa);

    // 增加账号
    @Insert(
        "insert into oat values(#{username},#{userid},#{password},#{sex},${astatus})")
    Integer addOperationalAccount(OperatingAccount oa);

    // 删除账号
    @Delete("delete from oat where userid=#{userid}")
    Integer deleteOperationalAccountByUserid(OperatingAccount oa);

    // 启用/禁用账号
    @Update("update oat set aStatus=#{astatus} where userid=#{userid}")
    Integer updateOperationalAccountStatusByUserid(OperatingAccount oa);

    // 修改账号信息
    @Update("update oat set sex=#{sex} where username=#{username}")
    Integer updateOperationalAccountByUsername(OperatingAccount oa);

    // 获取最大用户编号
    @Select("select MAX(userid) as userid from oat")
    List<OperatingAccount> getMaxuserID();

    // 重置密码
    @Update("update oat set password='123456' where userid=#{userid}")
    Integer resetOperationalAccountPasswordByUserid(OperatingAccount oa);

    // 多条件查询,见OperatingAccountDao.xml
    List<OperatingAccount> getOperationalAccountByMultipleConditions(OperatingAccount oa);
}

OperatingAccountServices.java

点击查看详细内容
package com.example.demo.services;

import com.example.demo.bean.OperatingAccount;

import java.util.Map;

public interface OperatingAccountServices {
    Map<String, Object> getAllAccounts(); // 01_获取所有账号信息

    Map<String, Object> getOperatingAccountByUsername(OperatingAccount oa); // 02_按照用户名获取账号信息

    Map<String, Object> getOperatingAccountByUserid(OperatingAccount oa); // 03_按照ID获取账号信息

    Integer addOperationalAccount(OperatingAccount oa); // 04_新增账号

    Integer deleteOperationalAccountByUserid(OperatingAccount oa);  // 05_按照ID删除账号

    Integer updateOperationalAccountByUsername(OperatingAccount oa);    //06_按照用户名更新账号信息

    Integer updateOperationalAccountStatusByUserid(OperatingAccount oa);    // 07_按照ID更新账号状态

    String getMaxUserid();  // 08_获取最大用户编号

    Integer resetOperationalAccountPasswordByUserid(OperatingAccount oa); // 09_按照ID重置密码

    Map<String, Object> getOperationalAccountByMultipleConditions(OperatingAccount oa); // 10_多条件查询
}

OperatingAccountServicesImpl.java

点击查看详细内容
package com.example.demo.services.impl;

import com.example.demo.bean.OperatingAccount;
import com.example.demo.dao.OperatingAccountDao;
import com.example.demo.services.OperatingAccountServices;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class OperatingAccountServicesImpl implements OperatingAccountServices {
    @Resource
    private OperatingAccountDao operatingAccountDao;

    @Override
    public Map<String, Object> getAllAccounts() {
        Map<String, Object> map = new HashMap<>();
        List<OperatingAccount> list = this.operatingAccountDao.getAllAccounts();
        if (list.size() > 0) {
            map.put("code", "0");
            map.put("list", list);
            map.put("count", list.size());
            map.put("message", "查询信息成功!");
            // 返回其他业务数据
        } else {
            map.put("code", "1");
            map.put("flag", false);
            map.put("count", list.size());
            map.put("message", "抱歉!没有您查询的信息!");
        }
        return map;
    }

    @Override
    public Map<String, Object> getOperatingAccountByUsername(OperatingAccount oa) {
        Map<String, Object> map = new HashMap<>();
        // 调用数据访问层的模块
        List<OperatingAccount> list = this.operatingAccountDao.getOperatingAccountByUsername(oa);
        if (list.size() > 0) {
            map.put("code", "0");
            map.put("list", list);
            map.put("count", list.size());
            map.put("message", "查询信息成功!");
            // 返回其他业务数据
        } else {
            map.put("code", "1");
            map.put("flag", false);
            map.put("count", list.size());
            map.put("message", "抱歉!没有您查询的信息!");
        }
        return map;
    }


    @Override
    public Map<String, Object> getOperatingAccountByUserid(OperatingAccount oa) {
        Map<String, Object> map = new HashMap<>();
        // 调用数据访问层的模块
        List<OperatingAccount> list = this.operatingAccountDao.getOperatingAccountByUserid(oa);
        if (list.size() > 0) {
            map.put("code", "0");
            map.put("list", list);
            map.put("count", list.size());
            map.put("message", "查询信息成功!");
            // 返回其他业务数据
        } else {
            map.put("code", "1");
            map.put("flag", false);
            map.put("count", list.size());
            map.put("message", "抱歉!没有您查询的信息!");
        }
        return map;
    }

    @Override
    public Integer addOperationalAccount(OperatingAccount oa) {
        Integer lines = this.operatingAccountDao.addOperationalAccount(oa);
        System.out.println("受影响的行:" + lines);
        return lines;
    }

    @Override
    public Integer deleteOperationalAccountByUserid(OperatingAccount oa) {
        Integer lines = this.operatingAccountDao.deleteOperationalAccountByUserid(oa);
        System.out.println("受影响的行:" + lines);
        return lines;
    }

    @Override
    public Integer updateOperationalAccountStatusByUserid(OperatingAccount oa) {
        Integer lines = this.operatingAccountDao.updateOperationalAccountStatusByUserid(oa);
        System.out.println("受影响的行:" + lines);
        return lines;
    }

    @Override
    public String getMaxUserid() {
        List<OperatingAccount> list = this.operatingAccountDao.getMaxuserID();
        return list.get(0).getUserid();
    }

    @Override
    public Integer resetOperationalAccountPasswordByUserid(OperatingAccount oa) {
        Integer lines = this.operatingAccountDao.resetOperationalAccountPasswordByUserid(oa);
        System.out.println("受影响的行:" + lines);
        return lines;
    }

    @Override
    public Integer updateOperationalAccountByUsername(OperatingAccount oa) {
        Integer lines = this.operatingAccountDao.updateOperationalAccountByUsername(oa);
        System.out.println("受影响的行:" + lines);
        return lines;
    }

    @Override
    public Map<String, Object> getOperationalAccountByMultipleConditions(OperatingAccount oa) {
        Map<String, Object> map = new HashMap<>();
        // 调用数据访问层的模块
        List<OperatingAccount> list = this.operatingAccountDao.getOperationalAccountByMultipleConditions(oa);
        if (list.size() > 0) {
            map.put("code", "0");
            map.put("list", list);
            map.put("count", list.size());
            map.put("message", "查询信息成功!");
            // 返回其他业务数据
        } else {
            map.put("code", "1");
            map.put("flag", false);
            map.put("count", list.size());
            map.put("message", "抱歉!没有您查询的信息!");
        }
        return map;
    }
}

DemoApplication.java

点击查看详细内容
package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;

@MapperScan(basePackages = {"com.example.demo.dao"})
@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

    public static void main(String[] args) {
        System.out.println("开始启动...");
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        System.out.println("启动成功!");
        /*获取项目本地地址 begin*/
        String port = (String) context.getBean("port");
        String path = (String) context.getBean("path");
        String page = "/login.html";
        String url = "http://localhost:" + port + path + page;
        System.out.println(url);
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows")) {
            /*自动打开浏览器 begin*/
            System.out.println("应用已经准备就绪 ... 正在打开浏览器并跳转至指定的页面 ... ");
            try {
                Runtime.getRuntime().exec("cmd /c start " + url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*自动打开浏览器 end*/
        }
        /*获取项目本地地址 end*/
    }
}

OperatingAccountDao.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.example.demo.dao.OperatingAccountDao">
    <select id="getOperationalAccountByMultipleConditions" resultType="OperatingAccount"
            parameterType="com.example.demo.bean.OperatingAccount">
        select * from oat
        <where>
            <if test="username != null and username != ''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="userid != null and userid != ''">
                and userid = #{userid}
            </if>
            <if test="sex != null and sex != ''">
                and sex in ${sex}
            </if>
            <if test="astatus == 0 or astatus != null and astatus != ''">
                and astatus = #{astatus}
            </if>
        </where>
    </select>
</mapper>

login.html

点击查看详细内容
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link rel="stylesheet" href="assets/css/login.css">
</head>
<body>
<div id="content" class="no-select">
    <div class="background"></div>
    <div class="title">
        <h3>万家乐</h3>
        <p>OCP全渠道数字平台运营后台</p>
    </div>
    <div class="register">
        <div class="register-guide">
            <h3>欢迎登录</h3>
            <p>忘记密码?<a href="#">联系管理员</a></p>
        </div>
        <div class="reg-content">
            <form autocomplete="off">
                <p id="p-username">
                    <label for="username" class="label-input">账 号</label>
                    <input id="username" type="text" name="username" class="text-input" autocomplete="off" value=""
                           placeholder="请输入账号" required autofocus onchange="check(this)">
                <div id="err-username" class="div-err">请输入正确账号</div>
                </p>
                <p id="p-password">
                    <label for="password" class="label-input">密 码</label>
                    <input id="password" type="password" name="password" class="text-input" autocomplete="off" value=""
                           placeholder="请输入密码" required onchange="check(this)">
                <div id="err-password" class="div-err">请输入正确密码,若忘记密码,请联系管理员</div>
                </p>
                <p id="p-submit">
                    <input id="button-submit" type="button" value="登录" class="button-submit" onclick="login()">
                </p>
            </form>
        </div>
    </div>
</div>
<script src="assets/js/jquery-3.5.0.js"></script>
<script src="assets/js/login.js"></script>
</body>
</html>

login.js

点击查看详细内容
var username = null, password = null, data = null;
var usr_is_err = true, pwd_is_err = true;

function checkAll() {
    if (!usr_is_err && !pwd_is_err) {	//账号密码都正确时,启用提交
        document.getElementById("p-submit").style.pointerEvents = "auto";
        document.getElementById("button-submit").style.background = "rgb(60, 113, 255)";
    } else {	//否则,禁用提交
        document.getElementById("p-submit").style.pointerEvents = "none";
        document.getElementById("button-submit").style.background = "rgb(189, 206, 252)";
    }
}

function check(obj) {
    var val = obj.valueOf().value;
    var id = obj.id;
    if (val !== "" && val !== undefined && val != null) {
        if (id === "username") {
            //一旦账号修改,自动清除密码
            document.getElementById("password").value = "";
            document.getElementById("err-password").style.visibility = "hidden";
            pwd_is_err = true;
            username = val;
            data = {username: username};
            //ajax去服务器端校验
            $.ajax({
                type: "POST",
                url: "hasaccount",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify(data),
                async: false,
                success: function (msg) {
                    if (msg === true) {
                        //账号存在
                        document.getElementById("err-username").style.visibility = "hidden";
                        usr_is_err = false;
                    } else if (msg === false) {
                        //账号不存在
                        document.getElementById("err-username").style.visibility = "visible";
                        usr_is_err = true;
                    }
                }
            });
        } else if (id === "password") {
            password = val;
            if (username == null) {     //刚打开页面的时候,如果只输入密码,会走这条分支
                document.getElementById("err-username").style.visibility = "visible";
            } else if (!usr_is_err) {    //只有账号正确才会走以下分支
                data = {username: username, password: password};
                $.ajax({
                    type: "POST",
                    url: "checkaccount",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(data),
                    async: false,
                    success: function (msg) {
                        if (msg === 2) {	//密码错误
                            document.getElementById("err-password").style.visibility = "visible";
                            pwd_is_err = true;
                        } else if (msg === 0) {	 //账号密码正确,但账号被禁用
                            //禁用提交
                            document.getElementById("err-password").style.visibility = "hidden";
                            document.getElementById("p-submit").style.pointerEvents = "none";
                            document.getElementById("button-submit").style.background = "rgb(189, 206, 252)";
                            alert("账号被禁用,请联系管理员!");
                            document.getElementById("password").value = "";
                            document.getElementById("err-password").style.visibility = "hidden";
                            pwd_is_err = true;
                        } else if (msg === 1) {	//账号密码正确
                            document.getElementById("err-password").style.visibility = "hidden";
                            usr_is_err = false;
                            pwd_is_err = false;
                        }
                    }
                });
            }
        }
    } else {
        if (id === "username") {
            username = null;
            usr_is_err = true;
            document.getElementById("err-username").style.visibility = "hidden";
        } else if (id === "password") {
            password = null;
            pwd_is_err = true;
            document.getElementById("err-password").style.visibility = "hidden";
        }
    }
    checkAll();
}

function login() {
    if (!usr_is_err && !pwd_is_err) {
        data = {username: username, password: password};
        $.ajax({
            type: "POST",
            url: "login",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data),
            async: false,
            success: function (msg) {   //账号密码正确,并且账号状态启用
                if (msg === 1) {
                    window.location.href = "index.html";
                } else if (msg === 0) {   //账号密码正确,但是账号状态禁用
                    alert("账号被禁用,请联系管理员!");
                    document.getElementById("password").value = "";
                    document.getElementById("err-password").style.visibility = "hidden";
                    pwd_is_err = true;
                    checkAll();
                }
            }
        });
    } else {
        alert("请检查账号密码");
    }
}

$(document).ready(function () {
    /*登录按钮动态更改样式 begin*/
    $(".button-submit").hover(function () {
        if (!usr_is_err && !pwd_is_err) {
            $(".button-submit").css("background", "rgb(72,85,255)");
        }
    }, function () {
        $(".button-submit").css("background", "rgb(60, 113, 255)");
    });
    /*登录按钮动态更改样式 end*/
});

/*光标处于输入密码框,按回车登录 begin*/
$("#password").bind("keyup", function (e) {
    //event.preventDefault() 方法阻止元素发生默认的行为。
    if (e.key === "Enter") {
        e.preventDefault();
        //按下回车后需要执行的函数,可以直接调用login函数
        login();
    }
});
/*光标处于输入密码框,按回车登录 end*/

index.html

点击查看详细内容
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>首页</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="assets/materialize/css/materialize.min.css" media="screen,projection"/>
    <link href="assets/css/bootstrap.css" rel="stylesheet"/>
    <link href="assets/css/font-awesome.css" rel="stylesheet"/>
    <link href="assets/js/morris/morris-0.4.3.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="assets/js/Lightweight-Chart/cssCharts.css">
    <!-- Custom Styles-->
    <link href="assets/css/custom-styles.css" rel="stylesheet"/>

    <script src="assets/js/jquery-1.10.2.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/materialize/js/materialize.min.js"></script>
    <script src="assets/js/jquery.metisMenu.js"></script>
    <script src="assets/js/morris/raphael-2.1.0.min.js"></script>
    <script src="assets/js/morris/morris.js"></script>
    <script src="assets/js/easypiechart.js"></script>
    <script src="assets/js/easypiechart-data.js"></script>
    <script src="assets/js/Lightweight-Chart/jquery.chart.js"></script>
    <!-- Custom Js -->
    <script src="assets/js/custom-scripts.js"></script>
    <script src="assets/js/myindex.js"></script>
</head>
<body>
<div id="wrapper">
    <nav class="navbar navbar-default top-navbar" role="navigation">
        <div class="navbar-header">
            <div class="navbar-brand waves-effect waves-dark">
                <img id="logo" src="assets/img/logo.png" alt="">
                <div id="sideNav" href=""><i class="material-icons dp48">toc</i></div>
            </div>
        </div>
        <div id="navInfo">OCP全渠道数字平台</div>
        <ul class="nav navbar-top-links navbar-right">
            <li><a class="dropdown-button waves-effect waves-dark" href="#" data-activates="dropdown1">
                <i class="fa fa-user fa-fw"></i> <b id="login_username_top">未登录</b>
                <i class="material-icons right">arrow_drop_down</i>
            </a></li>
        </ul>
    </nav>
    <ul id="dropdown1" class="dropdown-content">
        <li><a onclick="logout()"><i class="fa fa-sign-out fa-fw"></i> 退出</a></li>
    </ul>
    <nav class="navbar-default navbar-side" role="navigation">
        <div class="sidebar-collapse">
            <ul class="nav" id="main-menu">
                <li>
                    <img id="headPic" src="assets/img/headpic.jpg" alt="">
                    <div id="showInfo">
                        <p class="username" id="login_username_left">未登录</p>
                    </div>
                </li>
                <li>
                    <a href="index.html" class="active-menu waves-effect waves-dark"><i
                        class="fa fa-dashboard"></i>首页</a>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-sitemap"></i>运营管理<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="Management_OA.html"><i class="fa fa-user" aria-hidden="true"></i>运营账号管理</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-users" aria-hidden="true"></i>运营角色管理</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-file"></i>退货订单管理<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#"><i class="fa fa-plus" aria-hidden="true"></i>退货申请</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-bars" aria-hidden="true"></i>查看退货订单</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-fw fa-table"></i>库存管理<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#"><i class="fa fa-plus" aria-hidden="true"></i>制定调拨单</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-bars" aria-hidden="true"></i>调拨单列表</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-fw fa-gear"></i>系统配置<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#">日志<span class="fa arrow"></span></a>
                            <ul class="nav nav-third-level">
                                <li><a href="#">修改说明</a></li>
                                <li><a href="#">查看日志</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
    <div id="page-wrapper">
        <div class="header">
            <h1 class="page-header">首页</h1>
            <ol class="breadcrumb">
                <li><a href="#">我的待办</a></li>
                <li><a href="#">快捷功能</a></li>
                <li><a href="#">常用信息平台</a></li>
                <li><a href="#">公告</a></li>
            </ol>
        </div>
        <div id="page-inner">
            <div id="todo">
                <div class="item-title">我的待办 <span>/ Pending Items</span></div>
                <div class="item-content">
                    <div><span class="fa fa-calendar"></span>待审核备货列表</div>
                    <div><span class="fa fa-calendar"></span>待复核备货列表</div>
                    <div><span class="fa fa-calendar"></span>待审核批发列表</div>
                    <div><span class="fa fa-calendar"></span>待复核批发列表</div>
                    <div><span class="fa fa-calendar"></span>待备货发货</div>
                    <div><span class="fa fa-calendar"></span>待批发发货</div>
                </div>
            </div>
            <div id="platform">
                <div class="item-title">常用信息平台 <span>/ Common Information Platform</span></div>
                <div class="item-content">
                    <div><img src="assets/img/CRM.png" alt=""/>CRM平台</div>
                    <div><img src="assets/img/ewt.png" alt=""/>etw平台</div>
                    <div><img src="assets/img/erp.png" alt=""/>erp平台</div>
                    <div><img src="assets/img/SCM.png" alt=""/>SCM平台</div>
                </div>
            </div>
            <div id="news">
                <div class="item-title">公告&nbsp;集团新闻</div>
                <ul class="item-content-3">
                    <li>2018届大学生校园招聘</li>
                    <li>万家乐社会招聘</li>
                    <li>关于公开选拔空气能事业部门部长的启示</li>
                    <li>2018届大学生校园招聘</li>
                    <li>万家乐社会招聘</li>
                    <li>关于公开选拔空气能事业部门部长的启示</li>
                </ul>
            </div>
            <div id="shortcuts">
                <div class="item-title">快捷功能 <span>/ Shortcuts</span></div>
                <div class="item-content-4">
                    <div>产品类别</div>
                    <div>账户维护</div>
                    <div>批发订单列表</div>
                    <div>待审核备货活动列表</div>
                    <div>运营后台菜单列表管理</div>
                    <div>经销商列表</div>
                    <div>可售商品维护</div>
                    <div>价格维护</div>
                    <div>经销商列表</div>
                </div>
            </div>
            <footer><p>Copyright &copy; 2021. 代码敲不队 All rights reserved.</p></footer>
        </div>
    </div>
</div>
</body>
</html>

myindex.js

点击查看详细内容
var map = null;
$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "getloginuser",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: null,
        async: false,
        success: function (msg) {
            map = msg;
            $('#login_username_top')[0].innerHTML = map["login_username"];
            $('#login_username_left')[0].innerHTML = map["login_username"];
        }
    });
});

function logout() {
    $.ajax({
        type: "POST",
        url: "logout",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: null,
        async: false,
        success: function (msg) {
            if (msg === 0) {
                window.location.href = "login.html";
            } else {
                alert("退出时发生了错误,请查看后台");
            }
        }
    });
}

Management_OA.html

点击查看详细内容
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>运营账号管理</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
    <link rel="stylesheet" href="assets/materialize/css/materialize.min.css" media="screen,projection"/>
    <link href="assets/css/bootstrap.css" rel="stylesheet"/>
    <link href="assets/css/font-awesome.css" rel="stylesheet"/>
    <link href="assets/js/morris/morris-0.4.3.min.css" rel="stylesheet"/>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'/>
    <link rel="stylesheet" href="assets/js/Lightweight-Chart/cssCharts.css"/>
    <!-- Custom Styles-->
    <link href="assets/css/custom-styles.css" rel="stylesheet"/>
    <script src="assets/js/jquery-1.10.2.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/materialize/js/materialize.min.js"></script>
    <script src="assets/js/jquery.metisMenu.js"></script>
    <script src="assets/js/morris/raphael-2.1.0.min.js"></script>
    <script src="assets/js/morris/morris.js"></script>
    <script src="assets/js/easypiechart.js"></script>
    <script src="assets/js/easypiechart-data.js"></script>
    <script src="assets/js/Lightweight-Chart/jquery.chart.js"></script>
    <!-- Custom Js -->
    <script src="assets/js/custom-scripts.js"></script>
    <script src="assets/js/Management_OA.js"></script>
    <script src="assets/js/myindex.js"></script>
</head>
<body>
<!-- 让整个页面变暗 -->
<div id="light-down">
    <!-- 会弹出的div -->
    <div id="div-edit2">
        <div class="div-edit-head">
            <p>编辑账号</p>
        </div>
        <div id="div-edit-content-oa">
            <div class="div-item-oa">
                <label for="username-edit"><span class="require">*</span>用&nbsp;&nbsp;户&nbsp;&nbsp;名</label>
                <input id="username-edit" type="text" autocomplete="off" value="" required disabled>
            </div>
            <div class="div-item-oa">
                <label for="userid-edit"><span class="require">*</span>账号编号</label>
                <input id="userid-edit" type="text" autocomplete="off" value="" required disabled>
            </div>
            <div class="div-item-oa">
                <label><span class="require">*</span>用户性别</label>
                <div id="div-item-radio">
                    <input type="radio" name="sex-edit" id="sex-edit-m" value="1">
                    <label for="sex-edit-m">男</label>
                    <input type="radio" name="sex-edit" id="sex-edit-f" value="0">
                    <label for="sex-edit-f">女</label><br>
                </div>
            </div>
        </div>
        <div class="div-edit-button">
            <span onclick="light_up_edit()"><i class="fa fa-times-circle" aria-hidden="true"> 取消</i></span>
            <span onclick="saveedit_oa()"><i class="fa fa-check-circle" aria-hidden="true"> 保存</i></span>
        </div>
    </div>
    <div id="div-add2">
        <div class="div-edit-head">
            <p>添加账号</p>
        </div>
        <div id="div-add-content">
            <div class="div-item">
                <label for="username-add"><span class="require">*</span>用&nbsp;&nbsp;户&nbsp;&nbsp;名</label>
                <input id="username-add" type="text" autocomplete="off" value="" required>
            </div>
            <div class="div-item-oa">
                <label><span class="require">*</span>用户性别</label>
                <div id="div-item-radio-add">
                    <input type="radio" name="sex-add" id="sex-add-m" value="1">
                    <label for="sex-add-m">男</label>
                    <input type="radio" name="sex-add" id="sex-add-f" value="0">
                    <label for="sex-add-f">女</label><br>
                </div>
            </div>
            <div class="div-edit-button">
                <span onclick="light_up_add()"><i class="fa fa-times-circle" aria-hidden="true"> 取消</i></span>
                <span onclick="saveadd_oa()"><i class="fa fa-check-circle" aria-hidden="true"> 保存</i></span>
            </div>
        </div>
    </div>
</div>
<div id="wrapper">
    <nav class="navbar navbar-default top-navbar" role="navigation">
        <div class="navbar-header">
            <div class="navbar-brand waves-effect waves-dark">
                <img id="logo" src="assets/img/logo.png" alt="">
                <div id="sideNav" href=""><i class="material-icons dp48">toc</i></div>
            </div>
        </div>
        <div id="navInfo">OCP全渠道数字平台</div>
        <ul class="nav navbar-top-links navbar-right">
            <li><a class="dropdown-button waves-effect waves-dark" href="#" data-activates="dropdown1">
                <i class="fa fa-user fa-fw"></i> <b id="login_username_top">未登录</b>
                <i class="material-icons right">arrow_drop_down</i>
            </a></li>
        </ul>
    </nav>
    <ul id="dropdown1" class="dropdown-content">
        <li><a onclick="logout()"><i class="fa fa-sign-out fa-fw"></i> 退出</a></li>
    </ul>
    <nav class="navbar-default navbar-side" role="navigation">
        <div class="sidebar-collapse">
            <ul class="nav" id="main-menu">
                <li>
                    <img id="headPic" src="assets/img/headpic.jpg" alt="">
                    <div id="showInfo">
                        <p class="username" id="login_username_left">未登录</p>
                    </div>
                </li>
                <li>
                    <a href="index.html" class="waves-effect waves-dark"><i class="fa fa-dashboard"></i>首页</a>
                </li>
                <li class="active">
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-sitemap"></i>运营管理<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level collapse in" aria-expanded="true">
                        <li>
                            <a href="Management_OA.html" class="active-menu"><i class="fa fa-user"
                                                                                aria-hidden="true"></i>运营账号管理</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-users" aria-hidden="true"></i>运营角色管理</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-file"></i>退货订单管理<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#"><i class="fa fa-plus" aria-hidden="true"></i>退货申请</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-bars" aria-hidden="true"></i>查看退货订单</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-fw fa-table"></i>库存管理<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#"><i class="fa fa-plus" aria-hidden="true"></i>制定调拨单</a>
                        </li>
                        <li>
                            <a href="#"><i class="fa fa-bars" aria-hidden="true"></i>调拨单列表<span class="fa arrow"></span></a>
                            <ul class="nav nav-third-level">
                                <li><a href="#">1</a></li>
                                <li><a href="#">2</a></li>
                                <li><a href="#">3</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#" class="waves-effect waves-dark"><i class="fa fa-fw fa-gear"></i>系统配置<span
                        class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#">日志<span class="fa arrow"></span></a>
                            <ul class="nav nav-third-level">
                                <li><a href="#">修改说明</a></li>
                                <li><a href="#">查看日志</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
    <div id="page-wrapper">
        <div class="header">
            <h1 class="page-header">运营账号管理</h1>
        </div>
        <div id="page-inner">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-action" id="card-action">运营账号列表</div>
                        <div class="card-content" id="card-content">
                            <div id="div-search2">
                                <label for="input_search0" class="input_search1">ID:</label>
                                <input id="input_search0" type="text" class="input_search2" autocomplete="off"
                                       placeholder="请输入" value="" onchange="getSearchVal(this)">
                                <label for="input_search1" class="input_search1">用户名:</label>
                                <input id="input_search1" type="text" class="input_search2" autocomplete="off"
                                       placeholder="请输入" value="" onchange="getSearchVal(this)">
                                <label for="input_select_sex" class="input_select1">性别:</label>
                                <select id="input_select_sex" name="input_select" class="input_select2"
                                        onchange="getSearchVal(this)">
                                    <option value="2">全部</option>
                                    <option value="1">男</option>
                                    <option value="0">女</option>
                                </select>
                                <label for="input_select_status" class="input_select1">账号状态:</label>
                                <select id="input_select_status" name="input_select" class="input_select2"
                                        onchange="getSearchVal(this)">
                                    <option value="2">全部</option>
                                    <option value="1">启用</option>
                                    <option value="0">禁用</option>
                                </select>
                                <span><a onclick="searchReset()"><i class="fa fa-eraser" aria-hidden="true"></i> 重置</a></span>
                                <span><a onclick="dosearch()"><i class="fa fa-search"
                                                                 aria-hidden="true"></i> 查找</a></span>
                            </div>
                            <hr class="my-hr">
                            <div id="div-operation" class="no-select">
                                <span><a onclick="light_down_add()"><i class="fa fa-plus-square" aria-hidden="true"></i> 添加账号</a></span>
                                <span><a onclick="deleteMultiple()"><i class="fa fa-trash-o" aria-hidden="true"></i> 删除账号</a></span>
                                <span><a onclick="enableMultiple()"><i class="fa fa-check" aria-hidden="true"></i> 启用账号</a></span>
                                <span><a onclick="disableMultiple()"><i class="fa fa-ban"
                                                                        aria-hidden="true"></i> 禁用账号</a></span>
                            </div>
                            <table class="table table-striped table-bordered table-hover my-table">
                                <thead class="my-thead">
                                <tr>
                                    <th class="th_check">
                                        <input type="checkbox" id="check_th" name="checkAll" onclick="checkAll(this)">
                                        <label class="check_th" for="check_th"></label>
                                    </th>
                                    <th class="th_userid">ID</th>
                                    <th class="th_username">用户名</th>
                                    <th class="th_sex">性别</th>
                                    <th class="th_status">账号状态</th>
                                    <th class="th_operation">操作</th>
                                </tr>
                                </thead>
                                <tbody id="result_or">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <footer><p>Copyright &copy; 2021. 代码敲不队 All rights reserved.</p></footer>
        </div>
    </div>
</div>
</body>
</html>

Management_OA.js

点击查看详细内容
var list, trs = "";
var data = null;

function getAllAccounts() {
    $.ajax({
        type: "GET",
        url: "getAllAccounts",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: null,
        async: false,
        success: function (msg) {
            if (msg.code === "0") {
                list = msg.list;
                trs = "";
                for (var i = 0; i < list.length; i++) {
                    trs += '<tr id="' + list[i].userid + '">' +
                        '   <td>' +
                        '       <input type="checkbox" id="check_th' + list[i].userid + '" name="check" onclick="checkOne()">' +
                        '       <label class="check_th" for="check_th' + list[i].userid + '"></label>' +
                        '   </td>' +
                        '   <td>' + list[i].userid + '</td>' +
                        '   <td>' + list[i].username + '</td>' +
                        '   <td>' + ((list[i].sex === "M") ? "男" : "女") + '</td>' +
                        '   <td>' + ((list[i].astatus === 1) ? "启用" : "禁用") + '</td>' +
                        '   <td class="td-operation no-select">' +
                        '   <div>' +
                        '       <a><i class="fa fa-trash-o" aria-hidden="true" title="删除账号" ' +
                        '             onclick="deleteOne(this)"></i></a>' +
                        '   </div>' +
                        '   <div>' +
                        '       <a><i class="fa fa-pencil" aria-hidden="true" title="编辑账号" ' +
                        '           onclick="edit_oa(this)"></i></a>' +
                        '   </div>' +
                        '   <div>' +
                        '       <a><i class="fa fa-key" aria-hidden="true" title="重置密码" ' +
                        '           onclick="resetPassword(this)"></i></a>' +
                        '   </div>' +
                        '</tr>';
                }
                $("#result_or").html("");
                $('#result_or').append(trs);
            }
        }
    });
}

$(document).ready(function () {
    getAllAccounts();
});

/*全选框 begin*/
var cks = document.getElementsByName("check");

//全选控制所有子框
function checkAll(ckAll) {
    for (var i = 0; i < cks.length; i++) {
        cks[i].checked = ckAll.checked;
    }
}

//通过子框控制全选
function checkOne() {
    //给每一个子框绑定一个点击事件,每次触发都判断是否全选
    for (var i = 0; i < cks.length; i++) {
        //循环每一个按钮的值,判断是否选中
        var flag = true;
        var ckArr = document.getElementsByName("check");
        for (var j = 0; j < ckArr.length; j++) {
            //有未选中即终止循环,修改标记
            if (!ckArr[j].checked) {
                flag = false;
                break;
            }
        }
        //通过标记控制全选
        document.getElementById("check_th").checked = flag;
    }
}

/*全选框 end*/

function deleteOne(obj) {
    var userid = $(obj).parents()[3].id;
    var username = $(obj).parents()[3].children[2].valueOf().innerHTML;
    if (window.confirm('确定要删除"' + username + '"吗?')) {
        //确定
        data = {userid: userid};
        $.ajax({
            type: "POST",
            url: "deleteOperationalAccountByUserid",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data),
            async: true,
            success: function (msg) {
                if (msg > 0) {   //移除元素
                    $("#" + userid).remove();
                } else {
                    alert("删除失败");
                }
            }, error: function (msg) {
                alert("删除失败");
                console.log(msg);
            }
        });
    } else {
        //取消
    }
}

function deleteMultiple() {
    if (window.confirm('确定要批量删除吗?')) {
        //确定
        var checks = $("[id^='check_thOA']");    //选择id以“check_thOR”开头的元素
        var to_delete_rid;
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked) {
                to_delete_rid = checks[i].id.slice(8);  //选取从8位开始之后的字符
                data = {userid: to_delete_rid};
                $.ajax({
                    type: "POST",
                    url: "deleteOperationalAccountByUserid",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(data),
                    async: false,
                    success: function (msg) {
                        if (msg > 0) {   //移除元素
                            $("#" + to_delete_rid).remove();
                        } else {
                            alert("删除失败");
                        }
                    }, error: function (msg) {
                        alert("删除失败");
                        console.log(msg);
                    }
                });
            }
        }
    } else {
        //取消
    }
}

//显示黑幕
function light_down() {
    document.getElementById("light-down").style.opacity = "1";
    document.getElementById("light-down").style.zIndex = "100";
}

//收起黑幕
function light_up() {
    document.getElementById("light-down").style.opacity = "0";
    document.getElementById("light-down").style.zIndex = "0";
}

//显示编辑面板
function light_down_edit() {
    light_down();
    document.getElementById("div-edit2").style.opacity = "1";
    document.getElementById("div-edit2").style.zIndex = "100";
}

//收起编辑面板
function light_up_edit() {
    document.getElementById("div-edit2").style.opacity = "0";
    document.getElementById("div-edit2").style.zIndex = "0";
    light_up();
}

//显示添加面板
function light_down_add() {
    light_down();
    document.getElementById("div-add2").style.opacity = "1";
    document.getElementById("div-add2").style.zIndex = "100";
}

//收起添加面板
function light_up_add() {
    document.getElementById("div-add2").style.opacity = "0";
    document.getElementById("div-add2").style.zIndex = "0";
    light_up();
}

function edit_oa(obj) {
    var userid = $(obj).parents()[3].id;
    data = {userid: userid};
    $.ajax({
        type: "POST",
        url: "getOperatingAccountByUserid",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify(data),
        async: false,
        success: function (msg) {
            if (msg.code === "0") {
                list = msg.list;
                var radio = document.getElementsByName("sex-edit");
                if (list[0].sex === "M") {
                    radio[0].checked = true;
                } else if (list[0].sex === "F") {
                    radio[1].checked = true;
                }
                $("#username-edit")[0].valueOf().value = list[0].username;
                $("#userid-edit")[0].valueOf().value = list[0].userid;
                light_down_edit();
            }
        }
    });
}

function saveedit_oa() {
    var radio = document.getElementsByName("sex-edit");
    var sex, username, userid;
    if (radio[0].checked) {
        sex = "M";
    } else if (radio[1].checked) {
        sex = "F";
    }
    username = $("#username-edit")[0].valueOf().value;
    userid = $("#userid-edit")[0].valueOf().value;
    data = {
        username: username,
        sex: sex
    };
    $.ajax({
        type: "POST",
        url: "updateOperationalAccountByUsername",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify(data),
        async: false,
        success: function (msg) {
            if (msg > 0) {   //修改页内元素
                var tr = $("#" + userid)[0];
                tr.children[3].innerHTML = (sex === "M" ? "男" : "女");
                light_up_edit()
            } else {
                alert("保存失败");
            }
        }
    });
}

function resetPassword(obj) {
    var username = $(obj).parents()[3].children[2].valueOf().innerHTML;
    if (window.confirm('确定要重置"' + username + '"的密码吗?')) {
        //确定
        var userid = $(obj).parents()[3].id;
        data = {userid: userid};
        $.ajax({
            type: "POST",
            url: "resetOperationalAccountPasswordByUserid",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data),
            async: false,
            success: function (msg) {
                if (msg > 0) {
                    alert("重置成功")
                } else {
                    alert("重置失败");
                }
            }
        });
    } else {
        //取消
    }
}

function clean_addinfo() {
    $("#sex-add-m")[0].checked = false;
    $("#sex-add-f")[0].checked = false;
    $("#username-add")[0].valueOf().value = "";
}

function saveadd_oa() {
    var ok;
    var username, sex;
    username = $("#username-add")[0].valueOf().value;
    var radio = document.getElementsByName("sex-add");
    if (radio[0].checked) {
        sex = "M";
    } else if (radio[1].checked) {
        sex = "F";
    } else {
        sex = null;
    }
    if (username == null || username === "" || sex == null) {
        ok = false;
    } else {
        ok = true;
    }
    if (ok) {
        data = {
            username: username,
            sex: sex
        };
        $.ajax({
            type: "POST",
            url: "addOperationalAccount",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data),
            async: false,
            success: function (msg) {
                if (msg.code === "0") { //修改元素
                    list = msg.list;
                    for (var i = 0; i < list.length; i++) {
                        var tr = '<tr id="' + list[i].userid + '">' +
                            '   <td>' +
                            '       <input type="checkbox" id="check_th' + list[i].userid + '" name="check" onclick="checkOne()">' +
                            '       <label class="check_th" for="check_th' + list[i].userid + '"></label>' +
                            '   </td>' +
                            '   <td>' + list[i].userid + '</td>' +
                            '   <td>' + list[i].username + '</td>' +
                            '   <td>' + ((list[i].sex === "M") ? "男" : "女") + '</td>' +
                            '   <td>' + ((list[i].astatus === 1) ? "启用" : "禁用") + '</td>' +
                            '   <td class="td-operation no-select">' +
                            '   <div>' +
                            '       <a><i class="fa fa-trash-o" aria-hidden="true" title="删除账号" ' +
                            '             onclick="deleteOne(this)"></i></a>' +
                            '   </div>' +
                            '   <div>' +
                            '       <a><i class="fa fa-pencil" aria-hidden="true" title="编辑账号" ' +
                            '           onclick="edit_oa(this)"></i></a>' +
                            '   </div>' +
                            '   <div>' +
                            '       <a><i class="fa fa-key" aria-hidden="true" title="重置密码" ' +
                            '           onclick="resetPassword(this)"></i></a>' +
                            '   </div>' +
                            '</tr>';
                    }
                    light_up_add();
                    clean_addinfo();
                    $('#result_or').append(tr);
                } else {
                    alert("添加失败");
                }
            }
        });
    } else {
        alert("带星号字段为必填项");
    }
}

function enableMultiple() {
    if (window.confirm('确定要批量启用吗?')) {
        //确定
        var checks = $("[id^='check_thOA']");    //选择id以“check_thOR”开头的元素
        var to_enable_rid;
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked) {
                to_enable_rid = checks[i].id.slice(8);  //选取从8位开始之后的字符
                data = {userid: to_enable_rid, astatus: 1};
                $.ajax({
                    type: "POST",
                    url: "updateOperationalAccountStatusByUserid",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(data),
                    async: false,
                    success: function (msg) {
                        if (msg > 0) {   //修改元素
                            $(checks[i]).parents()[1].children[4].valueOf().innerText = "启用";
                        } else {
                            alert("启用失败");
                        }
                    }
                });
            }
        }
    } else {
        //取消
    }
}

function disableMultiple() {
    if (window.confirm('确定要批量禁用吗?')) {
        //确定
        var checks = $("[id^='check_thOA']");    //选择id以“check_thOR”开头的元素
        var to_disable_rid;
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked) {
                to_disable_rid = checks[i].id.slice(8);  //选取从8位开始之后的字符
                data = {userid: to_disable_rid, astatus: 0};
                $.ajax({
                    type: "POST",
                    url: "updateOperationalAccountStatusByUserid",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(data),
                    async: false,
                    success: function (msg) {
                        if (msg > 0) {   //修改元素
                            $(checks[i]).parents()[1].children[4].valueOf().innerText = "禁用";
                        } else {
                            alert("启用失败");
                        }
                    }
                });
            }
        }
    } else {
        //取消
    }
}

var search_userid = "", search_username = "", search_sex = 2, search_astatus = 2;

function getSearchVal(obj) {
    var val = obj.valueOf().value;
    var id = obj.id;
    if (id === "input_search0") {
        search_userid = val;
    } else if (id === "input_search1") {
        search_username = val;
    } else if (id === "input_select_sex") {
        search_sex = val;
    } else if (id === "input_select_status") {
        search_astatus = val;
    }
}

function searchReset() {
    search_userid = "";
    search_username = "";
    search_sex = 2;
    search_astatus = 2;
    $("#input_search0")[0].valueOf().value = "";
    $("#input_search1")[0].valueOf().value = "";
    $("#input_select_sex")[0].value = "2";
    $("#input_select_status")[0].value = "2";
}

function dosearch() {
    if (search_userid === "" && search_username === "" && search_sex === 2 && search_astatus === 2) {
        // 搜索值为默认值时,查找所有账号
        getAllAccounts();
    } else {
        // 能进入到这个分支,则至少有一个条件不为默认值
        data = {
            userid: search_userid,
            username: search_username,
            sex: search_sex,
            astatus: search_astatus
        };
        $.ajax({
            type: "POST",
            url: "getOperationalAccountByMultipleConditions",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data),
            async: true,
            success: function (msg) {
                if (msg.code === "0") {
                    list = msg.list;
                    trs = "";
                    for (var i = 0; i < list.length; i++) {
                        trs += '<tr id="' + list[i].userid + '">' +
                            '   <td>' +
                            '       <input type="checkbox" id="check_th' + list[i].userid + '" name="check" onclick="checkOne()">' +
                            '       <label class="check_th" for="check_th' + list[i].userid + '"></label>' +
                            '   </td>' +
                            '   <td>' + list[i].userid + '</td>' +
                            '   <td>' + list[i].username + '</td>' +
                            '   <td>' + ((list[i].sex === "M") ? "男" : "女") + '</td>' +
                            '   <td>' + ((list[i].astatus === 1) ? "启用" : "禁用") + '</td>' +
                            '   <td class="td-operation no-select">' +
                            '   <div>' +
                            '       <a><i class="fa fa-trash-o" aria-hidden="true" title="删除账号" ' +
                            '             onclick="deleteOne(this)"></i></a>' +
                            '   </div>' +
                            '   <div>' +
                            '       <a><i class="fa fa-pencil" aria-hidden="true" title="编辑账号" ' +
                            '           onclick="edit_oa(this)"></i></a>' +
                            '   </div>' +
                            '   <div>' +
                            '       <a><i class="fa fa-key" aria-hidden="true" title="重置密码" ' +
                            '           onclick="resetPassword(this)"></i></a>' +
                            '   </div>' +
                            '</tr>';
                    }
                    $("#result_or").html("");
                    $('#result_or').append(trs);
                } else {
                    $("#result_or").html("");
                }
            }
        });
    }
}

结尾

目前我还是初学者,如果哪里有错或者不妥的地方,还请大家在评论区交流指出。

posted @ 2021-02-02 14:46  吃猫的鱼℘  阅读(1206)  评论(0编辑  收藏  举报
Document