登录功能简单实现

前端login.vue

登录按钮触发,以表格提交form 表格ref=“loginForm” :model=“loginForm” ,前端login.vue网页。

<template>
  <div class="loginBody">
    <div class="loginDiv">
      <div class="login-content">
        <h1 class="login-title">用户登录</h1>
        <el-form center :model="loginForm" label-width="100px" :rules="rules" ref="loginForm">
          <el-form-item label="账号" prop="account"><el-input type="text" style="width: 200px" v-model="loginForm.account"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password"><el-input type="password" v-model="loginForm.password"
              style="width: 200px" show-password autocomplete="off" @keyup.enter="confirm"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button style="margin-left: 60px" type="primary" @click="confirm"
              :disabled="confirm_disabled">登录</el-button>
          </el-form-item>
          <div class="unlogin" style="text-align: center">
            <router-link :to="{ path: '/forgetpwd' }"> 忘记密码? </router-link>
            |
            <router-link :to="{ path: '/register' }">
              <a href="register.vue" target="_blank" align="right">注册新账号</a>
            </router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script scoped>
export default {
  name: 'Login',
  data() {
    return {
      confirm_disabled: false,
      loginForm: {
        account: '',
        password: '',
      },
      rules: {
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
    };
  },
  methods: {
    confirm() {
      this.confirm_disabled = true;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$axios
            .post(this.$httpUrl + '/user/login', this.loginForm)
            .then((res) => res.data)
            .then((res) => {
              if (res.code == 200) {
                sessionStorage.setItem('User', JSON.stringify(res.data.user));
                this.$store.dispatch('updateMenu', res.data.menu);
                this.$router.replace('/Index');
              } else {
                this.confirm_disabled = false;
                alert('用户名或密码错误!');
                return false;
              }
            });
        } else {
          this.confirm_disabled = false;
          console.log('校验失败');
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.loginBody {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #b3c0d1;
}

.loginDiv {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  width: 450px;
  height: 330px;
  background: #fff;
  border-radius: 5%;
}

.login-title {
  margin: 20px 0;
  text-align: center;
}

.login-content {
  width: 400px;
  height: 250px;
  position: absolute;
  top: 25px;
  left: 25px;
}
</style>

这上面的代码当然都是放login.vue里的,嘿嘿,分开点好看点。

前端代码运行

右键点击你的web项目选择在集成终端中打开
在这里插入图片描述

然后输入npm run serve,出现下图ctrl+左键点击进入前端页面。
在这里插入图片描述

后端代码

vscode中 java依赖下载

我大致数了下有七个嘿嘿
在这里插入图片描述
在这里插入图片描述

pom.xml

  		<!-- springboot web 那些getmapping注解啥的 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		<!-- 数据库mysql8及以上 -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- 实体类get,set,构造方法帮助搭建的依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- src /test 搭建测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- sprinboot2下载mybatis-plus依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.9</version>
        </dependency>    

controller

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/hello")
    public String hello() {
        return "hello wms";
    }

    @Autowired
    private IUserService userService;
    @Autowired
    private MenuService menuService;

    // 登录
    @PostMapping("/login")
    public Result Login(@RequestBody User user) {
        List<User> list = userService.lambdaQuery().eq(User::getAccount, user.getAccount())
                .eq(User::getPassword, user.getPassword()).list();
        if (list.size() > 0) {
            User user1 = (User) list.get(0);
            List<Menu> menuList = menuService.lambdaQuery().like(Menu::getMenuright, user1.getRoleId()).list();
            HashMap<String, Object> res = new HashMap<>();
            res.put("user", user1);
            res.put("menu", menuList);
            return Result.suc(res);
        }
        return Result.fail();
    }
}

嘿嘿你看见了我的封装类吧 result,这也解释了为啥我的axios获取数据要两个then才能获取到,因为我自己封装了一层嘛。

package com.example.wsm.common;

import lombok.Data;

@Data
public class Result {
    private int code; // 编码 200/400
    private String msg;// 成功/失败
    private Long total;// 总记录数
    private Object data;// 数据

    public static Result fail() {
        return result(400, "失败", 0L, null);
    }

    public static Result suc() {
        return result(200, "成功", 0L, null);
    }

    public static Result suc(Object data) {
        return result(200, "成功", 0L, data);
    }

    public static Result suc(Long total, Object data) {
        return result(200, "成功", total, data);
    }

    private static Result result(int code, String msg, Long total, Object data) {
        Result res = new Result();
        res.setCode(code);
        res.setMsg(msg);
        res.setTotal(total);
        res.setData(data);
        return res;
    }
}

数据库配置文件application.yml

server:
  port: 8090

spring:
  datasource:
  #这是我的数据库路径配置 我的数据库是mysql8.2 8以上的driver-class-name都用的下面这个名称了
    url: jdbc:mysql://localhost:3306/wsm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root

mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
#配置日志
  configuration.log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

CodeGenerator类代码自动生成

mybatis可以不用写xml,用sql语言封装好了的,创个entity实体类,service,impl,mapper,mapper实现类xml,我这些其实是用MyBatisplus里的CodeGenerator代码自动生成的。只需在数据库创建表,然后在后端运行代码输入该表名称就会自动生成entity,service,impl,mapper,mapper实现类xml,如果运行不了,那就是你还有啥依赖没下载哦。

mybatis-plus下载

要有springboot的依赖,springboot2 mybatisplus依赖用maven下载

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.9</version>
</dependency>

springboot3 mybaitsplus依赖用 maven 下载

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
    <version>3.5.9</version>
</dependency>

CodeGenerator代码

package com.example.wsm.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        try (Scanner scanner = new Scanner(System.in)) {
            StringBuilder help = new StringBuilder();
            help.append("请输入" + tip + ":");
            System.out.println(help.toString());
            if (scanner.hasNext()) {
                String ipt = scanner.next();
                if (StringUtils.isNotBlank(ipt)) {
                    return ipt;
                }
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + "/wsm";// 新加了+"/wsm"
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("wms");
        gc.setOpen(false);
        gc.setSwagger2(true); // 实体属性 Swagger2 注解
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);// xml columlist
        // 去掉service接口首字母的I,如DO为User则叫UserService
        gc.setServiceImplName("%sService");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/wsm?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.example.wsm") // 设置父包名
                .setMapper("mapper") // 设置Mapper接口所在的子包名
                .setEntity("entity") // 设置实体类所在的子包名
                .setService("service")
                .setServiceImpl("service.impl")
                .setController("controller"); // 设置Controller所在的子包名
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
         * cfg.setFileCreate(new IFileCreate() {
         * 
         * @Override
         * public boolean isCreate(ConfigBuilder configBuilder, FileType fileType,
         * String filePath) {
         * // 判断自定义文件夹是否需要创建
         * checkDir("调用默认方法创建的目录,自定义目录用");
         * if (fileType == FileType.MAPPER) {
         * // 已经生成 mapper 文件判断存在,不想重新生成返回 false
         * return !new File(filePath).exists();
         * }
         * // 允许生成模板文件
         * return true;
         * }
         * });
         */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        // 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // // 写于父类中的公共字段
        // strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

后端运行代码

运行一个×××Application.java结尾的。

自动生成的内容

后面的其实你可以不用看了,如果你运行了代码生成器,下面的都是自动生成的实体类,服务类,实现类。

package com.example.wsm.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 
 * </p>
 *
 * @author wms
 * @since 2024-06-18
 */
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "User对象", description = "")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主键")
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "账号")
    private String account;

    @ApiModelProperty(value = "名字")
    private String name;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "头像")
    private String image;

    @ApiModelProperty(value = "年龄")
    private Integer age;

    @ApiModelProperty(value = "性别")
    private Integer sex;

    @ApiModelProperty(value = "电话")
    private String phone;

    @ApiModelProperty(value = "角色 0超级管理员,1管理员,2用户")
    private Integer roleId;

    @ApiModelProperty(value = "是否有效 Y 有效,其他无效")
    @TableField("isValid")
    private String isvalid;
}
package com.example.wsm.service;
import com.example.wsm.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author wms
 * @since 2024-06-18
 */
public interface IUserService extends IService<User> {

}
package com.example.wsm.service.impl;

import com.example.wsm.entity.User;
import com.example.wsm.mapper.UserMapper;
import com.example.wsm.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wms
 * @since 2024-06-18
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {

package com.example.wsm.mapper;
import com.example.wsm.entity.User;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author wms
 * @since 2024-06-18
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

}
<?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.wsm.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.example.wsm.entity.User">
        <id column="id" property="id" />
        <result column="account" property="account" />
        <result column="name" property="name" />
        <result column="password" property="password" />
        <result column="image" property="image"/>
        <result column="age" property="age" />
        <result column="sex" property="sex" />
        <result column="phone" property="phone" />
        <result column="role_id" property="roleId" />
        <result column="isValid" property="isvalid" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, account, name, password,image, age, sex, phone, role_id, isValid
    </sql>
</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值