Springboot+VUE to realize login and registration

Springboot+VUE to realize login and registration

This article example shares the specific code of springboot+VUE to implement login and registration for your reference. The specific content is as follows

1. springBoot

Create a springBoot project

It is divided into three packages, namely controller, service, dao and xml files under the resource directory.

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("Someone requested to register!");
        int res = userService.register(user.getAccount(), user.getPassword());
        if(res==1) {
            return "Registration successful";
        } else {
            return "Registration failed";
        }
    }

    @PostMapping("/login/")
    @CrossOrigin("*")
    String login(@RequestBody User user) {
        int res = userService.login(user.getAccount(), user.getPassword());
        if(res==1) {
            return "Login successful";
        } else {
            return "Login failed";
        }
    }
}

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 (I installed the lombok plugin)

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>

Backbone Configuration

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

The database needs to create a corresponding table

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;

2. Create a VUE project

Install node, npm, and configure environment variables.
Configure the cnpm repository to make downloading faster.

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

Install VUE

npm i -g vue-cli

Initialize the package structure

vue init webpack project

Start a Project

# Enter the project directory cd vue-01
# Compile npm install
# Start npm run dev

Modify the project file according to the following structure

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="Please enter your account number"></el-input>
    <el-input v-model="password" placeholder="Please enter your password" show-password></el-input>
    <el-button type="primary" @click="login">Login</el-button>
    <el-button type="primary" @click="register">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('Login successful');
      }).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', //Domain name of the backend interface// secure: false, //If it is an https interface, you need to configure this parameter changeOrigin: true, //If the interface is cross-domain, you need to configure this parameter pathRewrite: {
          '^/api': '' //Path rewriting, when your URL contains the api field, such as /api/v1/tenant,
          //You can rewrite the path to the same name as the rule, which means you don't need to add the API during development.}
      }
    },

    // 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
  }
} 

Enter your account and password to implement simple registration and login functions.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Android uses OKhttp3 to implement login and registration functions + springboot to build the backend detailed process
  • SpringBoot+Mybatis to implement login and registration sample code
  • Solutions to common problems in SpringBoot login and registration
  • Springboot combines global exception handling to implement login and registration verification
  • SpringBoot implements a simple login and registration project

<<:  Tutorial on installing jdk1.8 on ubuntu14.04

>>:  How to reset the password if the Ubuntu 18.04 server password is forgotten or tampered with

Recommend

SQL implements LeetCode (180. Continuous numbers)

[LeetCode] 180. Consecutive Numbers Write a SQL q...

The process of deploying and running countly-server in docker in win10

I have just come into contact with and become fam...

Docker implements container port binding local port

Today, I encountered a small problem that after s...

How to implement variable expression selector in Vue

Table of contents Defining the HTML structure Inp...

Example of stars for CSS rating effect

What? What star coat? Well, let’s look at the pic...

How to quickly paginate MySQL data volumes of tens of millions

Preface In backend development, in order to preve...

Detailed explanation of the correct way to install opencv on ubuntu

This article describes how to install opencv with...

MySQL Installer Community 5.7.16 installation detailed tutorial

This article records the detailed tutorial of MyS...

Use of Linux crontab command

1. Command Introduction The contab (cron table) c...

CentOS 7 builds hadoop 2.10 high availability (HA)

This article introduces how to build a high-avail...

The reason why MySQL uses B+ tree as its underlying data structure

We all know that the underlying data structure of...

Centos7.5 installs mysql5.7.24 binary package deployment

1. Environmental preparation: Operating system: C...

An example of implementing a simple finger click animation with CSS3 Animation

This article mainly introduces an example of impl...