springboot+VUE 로그 인 등록 실현

11368 단어 vue로그 인책.
본 논문 의 사례 는 springboot+VUE 가 로그 인 등록 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
스프링 부츠
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;
2.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
프로젝트 파일 을 다음 과 같은 구조 로 수정 합 니 다.

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

계 정 비밀 번 호 를 입력 하여 간단 한 등록,로그 인 기능 을 실현 합 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기