欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot 学习2.4--实现用户管理功能

程序员文章站 2022-04-26 10:00:48
...

使用SpringBoot提供的Restful接口与Ajax异步通信技术实现服务器与数据库连接,并可以封装调用数据库执行语句,进行对数据库执行CRUD的操作。

这里演示的是对User表执行的插入、查询、修改与删除操作,实现了用户注册与登录功能,并实现了管理员与用户信息的管理。

1.首先在数据库中创建用户User表,具有用户名、密码、身份以及账号创建时间字段。

Demo:

Use demo;
create table `User`(
	`id` int(10) auto_increment not null,
	`UserName` varchar(20) not null,
	`Password` varchar(16) not null,
        `role` varchar(3)  not null,
	`create_date` DATE,
	PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.使用IDEA开发工具,创建SpringBoot项目。

在resource文件中写入以下代码与MySQL进行连接:

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456        //以个人自定义密码为准
spring.datasource.driverClassName=com.mysql.jdbc.Driver

3.在pom.xml中添加以下依赖:

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <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.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.22</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

等待IDEA自动将以上依赖下载完成。

4.创建Dao、Controller、Model文件夹

项目文件目录如下:

SpringBoot 学习2.4--实现用户管理功能

Dao层用于接收Controller类传递的参数,并提供Mapper接口、Mapper接口实现、xml封装数据库执行语句。

创建User实体类,字段与User表中一一对应:

import java.util.Date;

public class User {
    private int id;
    private String UserName;
    private String Password;
    private String role;
    private Date create_time;

    public Date getCreate_time() {
        return create_time;
    }

    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String password) {
        Password = password;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public User(int id, String userName, String password, String role) {
        this.id = id;
        UserName = userName;
        Password = password;
        this.role = role;
    }
}

在Dao层中的UserMapper接口中提供以下方法,用于接收控制器类获取到的参数,并提供给上层方法调用此接口:

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

@Mapper
public interface UserMapper {
    //用户登陆,返回用户名与用户加密后的密码
    Map<String, Object> UserLogin(@Param(value = "UserName") String UserName);
    //获取所有用户信息
    List<User> getAllUserInfo();
    //注册用户
    int AddUser(Map<String, Object> param);
    //更新用户信息
    int UpdateUserInfo(Map<String ,Object> param);
    //删除用户信息
    int DeleteUserInfo(Map<String, Object> param);
}

UserServiceImp实现了以上接口的方法,调用UserMapper.xml中封装的SQL语句:

UserServiceImp:

Service
public class UserServiceImp {

    @Resource
    @Autowired
    UserMapper userMapper;
    public Map<String, Object> UserLogin(String UserName) {
        return userMapper.UserLogin(UserName);
    }

    public int AddUser(Map<String, Object> param){
        return userMapper.AddUser(param);
    }

    public List<User> getAllUserInfo()
    {
        return userMapper.getAllUserInfo();
    }

    public int UpdateUserInfo(Map<String, Object>param){
        return userMapper.UpdateUserInfo(param);
    }

    public int DeleteUserInfo(Map<String, Object> param){
        return userMapper.DeleteUserInfo(param);
    }
}

UserMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo01.dao.User.UserMapper">
    
    <select id="getAllUserInfo" resultType="com.example.demo01.model.Goods">
            select * from `user` ORDER BY create_time desc LIMIT 1000
    </select>

    <insert id="AddUser" parameterType="map">
        INSERT into `user` (UserName,Password,role,create_time) values (#{UserName},#{Password},#{role},#{create_time})
    </insert>

    <select id="UserLogin" parameterType="string" resultType="map">
        select UserName,Password,role from user where UserName = #{UserName} limit 1
    </select>
    
    <update id="UpdateUserInfo" parameterType="map">
        UPDATE user set UserName = #{UserName},Password = #{Password},role = #{role} where id = #{id}
    </update>

    <delete id="DeleteUserInfo" parameterType="string">
        delete * from user where id = #{id}
    </delete>
</mapper>

Controller控制器类提供了给Ajax远程调用的API接口,用于接收用户在网页提交的参数,并调用对应的方法实现用户需要执行的操作:

package com.example.demo01.controller;

import com.example.demo01.dao.User.UserServiceImp;
import com.example.demo01.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    UserServiceImp userServiceImp;

    //获取所有用户信息
    @ResponseBody
    @RequestMapping(value = "/getAllUserInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin
    public List<User> getUser()
    {
        List<User> users = userServiceImp.getAllUserInfo();
        return users;
    }

    //用户登录
    @RequestMapping(value = "/UserLogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin
    private String UserLogin(@RequestBody String LoginJSON) throws Exception {
        JSONObject LoginJson = JSONObject.parseObject(LoginJSON);
        //获取登录名与登录密码
        String LoginNameInfo = LoginJson.getString("UserName");
        String LoginPasswordInfo = LoginJson.getString("Password");
        Map<String,Object> userInfo = userServiceImp.UserLogin(LoginNameInfo);
        JSONObject jsonObject = new JSONObject();
        System.out.println(LoginNameInfo);
        System.out.println(LoginPasswordInfo);
        if(userInfo == null){
            jsonObject.put("flag","0");
            jsonObject.put("msg","账号不存在!");
            return jsonObject.toString();
        }
        else{
            String UserName = (String) userInfo.get("UserName");
            String Password = (String)userInfo.get("Password");
            System.out.println(UserName);
            System.out.println(Password);
            if(LoginPasswordInfo.equals(Password)){
                jsonObject.put("flag",1);
                jsonObject.put("msg","登录成功!");
            }
            else {
                jsonObject.put("flag", "0");
                jsonObject.put("msg", "账号或者密码错误");
            }
        }
        return jsonObject.toString();
    }

    //用户注册
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @CrossOrigin
    private String AddUser(@RequestBody String addJSON) throws Exception{
        JSONObject AddJson = JSONObject.parseObject(addJSON);
        String UserName = AddJson.getString("UserName");
        String Password = AddJson.getString("Password");
        String role = "0"; //权限默认是0,管理员可修改权限
        SimpleDateFormat create_time = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        System.out.println(UserName);
        System.out.println(Password);
        System.out.println(role);
        System.out.println(create_time);
        Map<String ,Object> param = new HashMap<>();
        param.put("UserName",UserName);
        param.put("Password",Password);
        param.put("role",role);
        param.put("create_time",create_time);
        JSONObject jsonObject = new JSONObject();
        try{
            userServiceImp.AddUser(param);
            jsonObject.put("flag","1");
            jsonObject.put("msg","注册成功");
        }catch (Exception e){
            userServiceImp.AddUser(param);
            jsonObject.put("flag","1");
            jsonObject.put("msg","注册成功");
        }
        return jsonObject.toString();
    }

    //修改用户信息
    @RequestMapping(value = "/UpdateUserInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin
    private String UpdateUserInfo(@RequestBody String UpdateJSON) throws Exception{
        JSONObject UpdateJson = JSONObject.parseObject(UpdateJSON);
        String UserName = UpdateJson.getString("UserName");
        String Password = UpdateJson.getString("Password");
        String id = UpdateJson.getString("id");
        String role = UpdateJson.getString("role");
        Map<String, Object> param = new HashMap<>();
        param.put("id",id);
        param.put("UserName",UserName);
        param.put("Password",Password);
        param.put("role",role);
        int result= userServiceImp.UpdateUserInfo(param);
        JSONObject jsonObject = new JSONObject();
        if(result == 1){
            jsonObject.put("flag","1");
            jsonObject.put("msg","更新成功");
        }else{
            jsonObject.put("flag","0");
            jsonObject.put("msg","更新失败");
        }
        return jsonObject.toString();
    }

    //删除用户
    @RequestMapping(value = "/DeleteUserInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin
    private String DeleteUserInfo(@RequestBody String DeleteJSON) throws Exception{
        JSONObject DeleteJson = JSONObject.parseObject(DeleteJSON);
        String id = DeleteJson.getString("id");

        Map<String ,Object> param = new HashMap<>();
        int i = Integer.parseInt(id);
        param.put("id",i);
        int result = userServiceImp.DeleteUserInfo(param);
        JSONObject jsonObject = new JSONObject();

        if (result !=0 ){
            jsonObject.put("flag","1");
            jsonObject.put("msg","删除成功");
        }else {
            jsonObject.put("flag","0");
            jsonObject.put("msg","删除失败");
        }
        return jsonObject.toString();
    }
}

5.前端代码

 建议创建一个前端工程文件,并创建static保存Javascript文件等静态资源,和templates用于保存html页面文件。

用户登录界面设计:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用户信息管理系统</title>
    <script type="application/javascript" src="../static/js/jquery-3.1.js"></script>
</head>

<body>
<div align="center"><p style="font-family: 'Adobe 楷体 Std R';font-size: xx-large">用户登录</p>
    <img style="width: 1200px;height: 400px; margin-left: -10px" src="../static/img/login.jpg" /></div>
        <div align="center">
            <form>
                <div>
                    <label style="font-size: x-large;margin-left: 30px">用户名: </label>
                        <input style="margin-left: 20px; font-size: large" id="username" type="text" name="name" required lay-verify="required" autocomplete="off" placeholder="请输入账号">
                </div>
                <div>
                    <label style="font-size: x-large; margin-left: 30px">密码: </label>
                        <input style="margin-left: 42px;font-size: large" id="password" type="password" name="password" required lay-verify="required" autocomplete="off" placeholder="请输入密码">
                </div><br>
                <div>
                    <button id="login" type="button" style="margin-left: 85px;font-size: 17px; border-width: 1px; border-color: black;height: 30px;width: 60px">登 录</button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <button id="register" type="button" style="font-size: 17px; border-width: 1px; border-color: black;height: 30px;width: 60px">注 册</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
<script type="application/javascript" src="../static/js/login.js"></script>
</html>

在static/js文件夹,创建名为login.js的文件:

$(document).ready(function(){
    var UserName;
    var Password;
	$("#register").click(function(){
		$("#register").mouseenter(function(){
            $("#register").css("background-color","WhiteSmoke");
        });
        $("#register").mouseleave(function(){
            $("#register").css("background-color","lightgray");
        });
		window.location.href="register.html";
	})
    $("#login").click(function () {
        $("#login").mouseenter(function(){
            $("#login").css("background-color","WhiteSmoke");
        });
        $("#login").mouseleave(function(){
            $("#login").css("background-color","lightgray");
        });
        UserName = $("#username").val();
        Password = $("#password").val();
        $.ajax
        ({
            async:true,
            type: "POST",
            url: "http://localhost:8080/UserLogin",
            dataType: "json",
            data: JSON.stringify({
                "UserName": UserName,
                "Password": Password,
            }),
            contentType: "application/json",
            success: function (data) {
                console.log(data);
                var flag = data.flag;
                if(flag == 1){
					var role = data.role;
                    alert(data.msg);
                    localStorage.setItem('UserName',UserName);
					localStorage.setItem('role',role);
                    window.location.href="index.html";
                }else{
                    alert("登录失败");
                }
            }
        })
    })
})

注册界面:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用户信息管理系统</title>
    <script type="application/javascript" src="../static/js/jquery-3.1.js"></script>
</head>

<body>
<div align="center"><p style="font-family: 'Adobe 楷体 Std R';font-size: x-large">用户信息管理系统-用户注册</p>
    <img style="width: 1200px;height: 400px; margin-left: -10px" src="../static/img/1.jpg" /></div>
<div align="center">
    <form>
        <div>
            <label style="font-size: x-large; margin-left: 30px">输入账号: </label>
            <input style="margin-left: 42px; font-size: large" id="username" type="text" name="name" required lay-verify="required" autocomplete="off" placeholder="请输入账号">
        </div>
        <div>
            <label style="font-size: x-large; margin-left: 30px">输入密码: </label>
            <input style="margin-left: 42px;font-size: large" id="password" type="password" name="password" required lay-verify="required" autocomplete="off" placeholder="请输入密码">
        </div>
        <div>
            <label style="font-size: x-large; margin-left: 30px">确认密码: </label>
            <input style="margin-left: 42px;font-size: large" id="confirm_password" type="password" name="password" required lay-verify="required" autocomplete="off" placeholder="确认密码">
        </div>
        <br>
        <div>
            <button id="register_btn" type="button" style="margin-left: 85px;font-size: 17px; border-width: 1px; border-color: black;height: 30px;width: 60px">注 册</button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <button id="back" type="button" style="font-size: 17px; border-width: 1px; border-color: black;height: 30px;width: 60px">返 回</button>
        </div>
    </form>
</div>
</div>
</div>
</body>
<script type="application/javascript" src="../static/js/register.js"></script>
</html>

Regitser.js:

$(document).ready(function(){
    var UserName;
    var Password;
    $("#register_btn").click(function () {
        $("#register_btn").mouseenter(function(){
            $("#register_btn").css("background-color","WhiteSmoke");
        });
        $("#register_btn").mouseleave(function(){
            $("#register_btn").css("background-color","lightgray");
        });
        UserName = $("#username").val();
        Password = $("#password").val();
        var confirm_pwd = $("#confirm_password").val();
        if(Password == confirm_pwd){
            $.ajax
            ({
                async:true,
                type: "POST",
                url: "http://localhost:8080/addUser",
                dataType: "json",
                data: JSON.stringify({
                    "UserName": UserName,
                    "Password": Password
                }),
                contentType: "application/json",
                success: function (data) {
                    console.log(data);
                    var flag = data.flag;
                    if(flag == 1){
                        alert(data.msg);
                        window.location.href = "login.html";
                    }else{
                        alert("注册失败");
                    }
                }
            })
        }
    })
    $("#back").click(function () {
        $("#back").mouseenter(function () {
            $("#back").css("background-color", "WhiteSmoke");
        });
        $("#back").mouseleave(function () {
            $("#back").css("background-color", "lightgray");
        });
        window.location.href="index.html";
    });
})