springboot+VUE实现登录注册


Posted in Vue.js onMay 27, 2021

本文实例为大家分享了springboot+VUE实现登录注册的具体代码,供大家参考,具体内容如下

一、springBoot

创建springBoot项目

分为三个包,分别为controller,service, dao以及resource目录下的xml文件。

UserController.java

package springbootmybatis.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springbootmybatis.pojo.User;
import springbootmybatis.service.UserService;

import javax.annotation.Resource;


@RestController
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/register/")
    @CrossOrigin("*")
    String register(@RequestBody User user) {
        System.out.println("有人请求注册!");
        int res = userService.register(user.getAccount(), user.getPassword());
        if(res==1) {
            return "注册成功";
        } else {
            return "注册失败";
        }
    }

    @PostMapping("/login/")
    @CrossOrigin("*")
    String login(@RequestBody User user) {
        int res = userService.login(user.getAccount(), user.getPassword());
        if(res==1) {
            return "登录成功";
        } else {
            return "登录失败";
        }
    }
}

UserService.java

package springbootmybatis.service;

import org.springframework.stereotype.Service;
import springbootmybatis.dao.UserMapper;

import javax.annotation.Resource;

@Service
public class UserService {
    @Resource
    UserMapper userMapper;

    public int register(String account, String password) {
        return userMapper.register(account, password);
    }

    public int login(String account, String password) {
        return userMapper.login(account, password);
    }
}

User.java (我安装了lombok插件)

package springbootmybatis.pojo;

import lombok.Data;

@Data
public class User {
    private String account;
    private String password;
}

UserMapper.java

package springbootmybatis.dao;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {
    int register(String account, String password);

    int login(String account, String password);
}

UserMapper.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="springbootmybatis.dao.UserMapper">

    <insert id="register">
       insert into User (account, password) values (#{account}, #{password});
    </insert>

    <select id="login" resultType="Integer">
        select count(*) from User where account=#{account} and password=#{password};
    </select>
</mapper>

主干配置

application.yaml

server.port: 8000
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/community?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
    type-aliases-package: springbootmybatis.pojo
    mapper-locations: classpath:mybatis/mapper/*.xml
    configuration:
      map-underscore-to-camel-case: true

数据库需要建相应得到表

CREATE TABLE `user` (
  `account` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `password` varchar(255) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

二、创建VUE项目

安装node,npm,配置环境变量。
配置cnpm仓库,下载的时候可以快一些。

npm i -g cnpm --registry=https://registry.npm.taobao.org

安装VUE

npm i -g vue-cli

初始化包结构

vue init webpack project

启动项目

# 进入项目目录
cd vue-01
# 编译
npm install
# 启动
npm run dev

修改项目文件,按照如下结构

springboot+VUE实现登录注册

APP.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>

</style>

welcome.vue

<template>
  <div>
    <el-input v-model="account" placeholder="请输入帐号"></el-input>
    <el-input v-model="password" placeholder="请输入密码" show-password></el-input>
    <el-button type="primary" @click="login">登录</el-button>
    <el-button type="primary" @click="register">注册</el-button>
  </div>
</template>

<script>
export default {
  name: 'welcome',
  data () {
    return {
      account: '',
      password: ''
    }
  },
  methods: {
    register: function () {
      this.axios.post('/api/register/', {
        account: this.account,
        password: this.password
      }).then(function (response) {
        console.log(response);
      }).catch(function (error) {
        console.log(error);
      });
      // this.$router.push({path:'/registry'});
    },
    login: function () {
      this.axios.post('/api/login/', {
        account: this.account,
        password: this.password
      }).then(function () {
        alert('登录成功');
      }).catch(function (e) {
        alert(e)
      })
      // this.$router.push({path: '/board'});
    }
  }
}
</script>

<style scoped>

</style>

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)
Vue.use(ElementUI)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>'
})

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import welcome from '@/components/welcome'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'welcome',
      component: welcome
    }
  ]
})

config/index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://localhost:8000', // 后端接口的域名
        // secure: false,  // 如果是https接口,需要配置这个参数
        changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
        pathRewrite: {
          '^/api': '' //路径重写,当你的url带有api字段时如/api/v1/tenant,
          //可以将路径重写为与规则一样的名称,即你在开发时省去了再添加api的操作
        }
      }
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

springboot+VUE实现登录注册

输入账号密码,实现简单的注册,登录功能。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Vue.js 相关文章推荐
vue3.0实现点击切换验证码(组件)及校验
Nov 18 Vue.js
Vue组件生命周期运行原理解析
Nov 25 Vue.js
vue3.0+vue-router+element-plus初实践
Dec 02 Vue.js
Vue过滤器,生命周期函数和vue-resource简单介绍
Jan 12 Vue.js
vue form表单post请求结合Servlet实现文件上传功能
Jan 22 Vue.js
Vite和Vue CLI的优劣
Jan 30 Vue.js
vue项目配置 webpack-obfuscator 进行代码加密混淆的实现
Feb 26 Vue.js
使用vue-element-admin框架从后端动态获取菜单功能的实现
Apr 29 Vue.js
如何使用vue3打造一个物料库
May 08 Vue.js
Vue接口封装的完整步骤记录
May 14 Vue.js
vue+elementui 实现新增和修改共用一个弹框的完整代码
Jun 08 Vue.js
一篇文章告诉你如何实现Vue前端分页和后端分页
Feb 18 Vue.js
vue+springboot实现登录验证码
vue+spring boot实现校验码功能
May 27 #Vue.js
vue-cropper组件实现图片切割上传
May 27 #Vue.js
vue-cropper插件实现图片截取上传组件封装
May 27 #Vue.js
HTML+VUE分页实现炫酷物联网大屏功能
Vue实现动态查询规则生成组件
详解vue身份认证管理和租户管理
You might like
php echo, print, print_r, sprintf, var_dump, var_expor的使用区别
2013/06/20 PHP
PHP7扩展开发之基于函数方式使用lib库的方法详解
2018/01/15 PHP
5 cool javascript apps
2007/03/24 Javascript
use jscript List Installed Software
2007/06/11 Javascript
jquery如何实现在加载完iframe的内容后再进行操作
2013/09/10 Javascript
director.js实现前端路由使用实例
2015/02/03 Javascript
jquery实现图片随机排列的方法
2015/05/04 Javascript
JS定义类的六种方式详解
2016/05/12 Javascript
3种不同的ContextMenu右键菜单实现代码
2016/11/03 Javascript
Bootstrap CSS布局之表格
2016/12/17 Javascript
Vue CLI3搭建的项目中路径相关问题的解决
2018/09/17 Javascript
傻瓜式解读koa中间件处理模块koa-compose的使用
2018/10/30 Javascript
使用Vue 实现滑动验证码功能
2019/06/27 Javascript
vue+openlayers绘制省市边界线
2020/12/24 Vue.js
[02:09]2018DOTA2亚洲邀请赛TNC赛前采访
2018/04/04 DOTA
[01:03:41]DOTA2-DPC中国联赛 正赛 Dynasty vs XG BO3 第三场 2月2日
2021/03/11 DOTA
python根据距离和时长计算配速示例
2014/02/16 Python
Python基于time模块求程序运行时间的方法
2017/09/18 Python
python-opencv 将连续图片写成视频格式的方法
2019/01/08 Python
python适合人工智能的理由和优势
2019/06/28 Python
python编写猜数字小游戏
2019/10/06 Python
浅析PEP570新语法: 只接受位置参数
2019/10/15 Python
Flask 上传自定义头像的实例详解
2020/01/09 Python
HTML5之SVG 2D入门7—SVG元素的重用与引用
2013/01/30 HTML / CSS
详解HTML5中的拖放事件(Drag 和 drop)
2016/11/14 HTML / CSS
澳大利亚在线生活方式商店:Mytopia
2018/07/08 全球购物
英国文具、办公用品和科技商店:Ryman
2018/09/27 全球购物
Simons官方网站:加拿大时尚零售商
2020/02/20 全球购物
实习教师自我鉴定
2013/12/09 职场文书
数控机械专业个人的自我评价
2014/01/02 职场文书
广告创意求职信
2014/03/17 职场文书
2015大学生党员自我评价范文
2015/03/03 职场文书
奖励通知
2015/04/22 职场文书
员工工作表扬信
2015/05/05 职场文书
幼儿园托班教育随笔
2015/08/14 职场文书
mysql中int(3)和int(10)的数值范围是否相同
2021/10/16 MySQL