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 相关文章推荐
vue使用exif获取图片旋转,压缩的示例代码
Dec 11 Vue.js
SpringBoot+Vue 前后端合并部署的配置方法
Dec 30 Vue.js
antdesign-vue结合sortablejs实现两个table相互拖拽排序功能
Jan 08 Vue.js
聊聊vue 中的v-on参数问题
Jan 29 Vue.js
关于vue中如何监听数组变化
Apr 28 Vue.js
Vue实现动态查询规则生成组件
May 27 Vue.js
vue-cropper插件实现图片截取上传组件封装
May 27 Vue.js
Vue中插槽slot的使用方法与应用场景详析
Jun 08 Vue.js
Vue-Element-Admin集成自己的接口实现登录跳转
Jun 23 Vue.js
vue实现锚点定位功能
Jun 29 Vue.js
前端vue+express实现文件的上传下载示例
Feb 18 Vue.js
Vue深入理解插槽slot的使用
Aug 05 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的preg_match匹配字符串长度问题解决方法
2014/05/03 PHP
jQuery get和post 方法传值注意事项
2009/11/03 Javascript
Jquery仿淘宝京东多条件筛选可自行结合ajax加载示例
2013/08/28 Javascript
javascript跨域的4种方法和原理详解
2014/04/08 Javascript
JavaScript实现页面跳转的几种常用方式
2015/11/28 Javascript
JavaScript html5 canvas画布中删除一个块区域的方法
2016/01/26 Javascript
AngularJS实现表格的增删改查(仅限前端)
2017/07/04 Javascript
10个在JavaScript开发中常遇到的BUG
2017/12/18 Javascript
JS引用传递与值传递的区别与用法分析
2018/06/01 Javascript
微信小程序动态增加按钮组件
2018/09/14 Javascript
Three.JS实现三维场景
2018/12/30 Javascript
Jquery属性的获取/设置及样式添加/删除操作技巧分析
2019/12/23 jQuery
[17:00]DOTA2 HEROS教学视频教你分分钟做大人-帕克
2014/06/10 DOTA
采用Psyco实现python执行速度提高到与编译语言一样的水平
2014/10/11 Python
python中的编码知识整理汇总
2016/01/26 Python
Python unittest模块用法实例分析
2018/05/25 Python
python使用正则表达式来获取文件名的前缀方法
2018/10/21 Python
python用plt画图时,cmp设置方法
2018/12/13 Python
Python求均值,方差,标准差的实例
2019/06/29 Python
使用python将excel数据导入数据库过程详解
2019/08/27 Python
Flask框架路由和视图用法实例分析
2019/11/07 Python
python数据预处理方式 :数据降维
2020/02/24 Python
Python切割图片成九宫格的示例代码
2020/03/10 Python
django admin 添加自定义链接方式
2020/03/11 Python
查看jupyter notebook每个单元格运行时间实例
2020/04/22 Python
win7上tensorflow2.2.0安装成功 引用DLL load failed时找不到指定模块 tensorflow has no attribute xxx 解决方法
2020/05/20 Python
python中adb有什么功能
2020/06/07 Python
matplotlib交互式数据光标实现(mplcursors)
2021/01/13 Python
澳大利亚汽车零部件、音响及配件超市:Automotive Superstore
2018/06/19 全球购物
即兴演讲稿
2014/01/04 职场文书
小学生防溺水广播稿
2014/01/12 职场文书
四年级科学教学反思
2014/02/10 职场文书
厨师长岗位职责范本
2014/08/25 职场文书
财务稽核岗位职责
2015/04/13 职场文书
通用员工手册范本
2015/05/14 职场文书
Python利用zhdate模块实现农历日期处理
2022/03/31 Python