SpringBoot+Mybatis +vue 实现登录 注册 还有验证码的。

不是前后端分离的

 

 

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link rel="stylesheet" href="../../css/base.css">
    <link rel="stylesheet" href="../../css/element.css">
</head>
<body style="background:url('../../images/bg.jpg') no-repeat; background-size: cover;">
    <div id="wrapper">
        <div style="width: 500px; margin: 150px auto; background-color:rgba(100,149,237,0.5); border-radius: 10px">
            <div style="width: 100%; height: 100px; font-size: 30px;line-height: 100px; text-align: center; color: darkblue">欢迎登录后台管理系统</div>
            <div style="margin-top: 25px; width: 100%; height: 320px;">
                <div style="width: 60%; margin: 0 auto">
                    <input v-model="user.username" type="text" style="border: 1px solid #ccc; height: 40px; padding: 10px; width: 100%" placeholder="请输入账号">
                    <input v-model="user.password" type="password" style="border: 1px solid #ccc; height: 40px; padding: 10px; width: 100%; margin-top: 25px" placeholder="请输入密码">
                    <div style="margin-top: 25px; line-height: 40px">
                        <input v-model="user.code" type="text" style="border: 1px solid #ccc; padding: 10px; width: 65%; " placeholder="请输入验证码">
                        <div id="picyzm" style="display: inline-block; height: 35px; vertical-align: middle;"></div>
                    </div>

                    <button @click="login" style="height: 40px; padding: 10px; width: 100%; margin-top: 25px; background-color: steelblue; color: white">登录</button>
                    <a style="width: 100%; text-align: right; display: inline-block; margin-top: 25px; color: darkblue" href="register.html">还没账号?去注册</a>
                </div>

            </div>
        </div>
    </div>

    <script src="../../js/jquery.min.js"></script>
    <script src="../../js/vue.min.js"></script>
    <script src="../../js/element.js"></script>
    <script src="../../js/gVerify.js"></script>

    <script>
        //初始化验证码
        let  verifyCode;

        new Vue({
            el: "#wrapper",
            data: {
                user: {}
            },
            mounted() {
                verifyCode = new GVerify({
                    id: "picyzm",
                    type: "blend"
                });
            },
            methods: {
                login() {
                    if (!this.user.username) {
                        this.$message({
                            message: "请输入用户名",
                            type: "error"
                        });
                        return;
                    }
                    if (!this.user.password) {
                        this.$message({
                            message: "请输入密码",
                            type: "error"
                        });
                        return;
                    }
                    if (!this.user.code) {
                        this.$message({
                            message: "请输入验证码",
                            type: "error"
                        });
                        return;
                    }
                    let res = verifyCode.validate(this.user.code);
                    if (!res) {
                        this.$message({
                            message: "验证码错误",
                            type: "error"
                        });
                        return;
                    }
                    $.ajax({
                        url: "/user/login",
                        type: "POST",
                        contentType: "application/json",
                        data: JSON.stringify(this.user)
                    }).then(res => {
                        if (res.code === '0') {
                            this.$message({
                                message: "登录成功",
                                type: "success"
                            });
                            sessionStorage.setItem("user", JSON.stringify(res.data));
                            setTimeout(() => {
                                location.href= "/page/end/index.html"
                            }, 1000)
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            })
                        }
                    })
                }
            }
        })

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

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <link rel="stylesheet" href="../../css/base.css">
    <link rel="stylesheet" href="../../css/element.css">
</head>
<body style="background:url('../../images/bg1.jpg') no-repeat; background-size: cover;">
    <div id="wrapper">
        <div style="width: 500px; margin: 150px auto;background-color:rgba(100,149,237,0.5); border-radius: 10px">
            <div style="width: 100%; height: 100px; color: darkblue; font-size: 30px;line-height: 100px; text-align: center">欢迎注册</div>
            <div style="margin-top: 25px; width: 100%; height: 350px; text-align: center">
                <input v-model="user.username" type="text" style="border: 1px solid #ccc; height: 40px; padding: 10px; width: 60%" placeholder="请输入账号">
                <input v-model="user.password" type="password" style="border: 1px solid #ccc; height: 40px; padding: 10px; width: 60%; margin-top: 20px" placeholder="请输入密码">
                <input v-model="user.email" type="text" style="border: 1px solid #ccc; height: 40px; padding: 10px; width: 60%;  margin-top: 20px" placeholder="请输入邮箱">
                <input v-model="user.phone" type="text" style="border: 1px solid #ccc; height: 40px; padding: 10px; width: 60%;  margin-top: 20px" placeholder="请输入电话">
                <button @click="register" style="height: 40px; padding: 10px; width: 60%; margin-top: 25px; background-color: steelblue; color: white">注册</button>
                <div style="margin-top: 25px">
                    <a style="width: 60%; text-align: right; display: inline-block; color: darkblue" href="login.html">已有账号,去登录</a>
                </div>
            </div>
        </div>
    </div>

    <script src="../../js/jquery.min.js"></script>
    <script src="../../js/vue.min.js"></script>
    <script src="../../js/element.js"></script>

    <script>
        new Vue({
            el: "#wrapper",
            data: {
                user: {}
            },
            methods: {
                register() {
                    if (!this.user.username) {
                        this.$message({
                            message: "请输入用户名",
                            type: "error"
                        });
                        return;
                    }
                    if (!this.user.password) {
                        this.$message({
                            message: "请输入密码",
                            type: "error"
                        });
                        return;
                    }
                    $.ajax({
                        url: "/user/register",
                        type: "POST",
                        contentType: "application/json",
                        data: JSON.stringify(this.user)
                    }).then(res => {
                        if (res.code === '0') {
                            this.$message({
                                message: "注册成功",
                                type: "success"
                            });
                            sessionStorage.setItem("user", JSON.stringify(res.data));
                            setTimeout(() => {
                                location.href= "/page/end/index.html"
                            }, 1000)
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            })
                        }
                    })
                }
            }
        })
    </script>
</body>
</html>

 

UserController.java

package com.example.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/user")
public class UserController {
    public static final ConcurrentHashMap<String, User> MAP = new ConcurrentHashMap<>();

    @Resource
    private UserService userService;


    /**
     * 登录
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody User user, HttpServletRequest request) {
        User res = userService.login(user);
        request.getSession().setAttribute("user", user);
        MAP.put(res.getUsername(), res);

        return Result.success(res);
    }

    /**
     * 注册
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user, HttpServletRequest request) {
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        User dbUser = userService.register(user);
        request.getSession().setAttribute("user", user);
        return Result.success(dbUser);
    }

    @GetMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            request.getSession().removeAttribute("user");
            MAP.remove(user.getUsername());
        }
        return Result.success();
    }

    @GetMapping("/online")
    public Result<Collection<User>> online(HttpServletRequest request) {
        return Result.success(MAP.values());
    }

    @PostMapping
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        return Result.success(userService.save(user));
    }

    @PutMapping
    public Result<?> update(@RequestBody User user) {
        return Result.success(userService.updateById(user));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Long id) {
        return Result.success(userService.getById(id));
    }

    @GetMapping("/detail/{username}")
    public Result<User> findByUsername(@PathVariable String username) {
        return Result.success(userService.getbyUsername(username));
    }

    @GetMapping
    public Result<List<User>> findAll() {
        return Result.success(userService.list());
    }

    @GetMapping("/page")
    public Result<IPage<User>> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return Result.success(userService.page(new Page<>(pageNum, pageSize),
                Wrappers.<User>lambdaQuery().like(User::getUsername, name).orderByDesc(User::getId)));
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<User> all = userService.list();
//        从userList集合中,依次取出一个对象
        for (User user : all) {
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("名称", user.getUsername());
            row1.put("手机", user.getPhone());
            row1.put("邮箱", user.getEmail());
            list.add(row1);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

}

实体类

public class User extends Model<User> {
    /**
      * 主键
      */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    private String username;

    private String password;

    private String email;

    private String phone;

    private String avatar;

userService


@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleService roleService;

    public User login(User user) {
        User one = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (one == null) {
            throw new CustomException("-1", "账号或密码错误");
        }
        setPermission(one);
        return one;
    }

    public User register(User user) {
        User one = getOne((Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername())));
        if (one != null) {
            throw new CustomException("-1", "用户已注册");
        }
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        save(user);
        return getOne((Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername())));
    }

userMapper

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

 

 

user.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.mapper.UserMapper">

</mapper>
Logo

前往低代码交流专区

更多推荐