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

修改项目文件,按照如下结构
在这里插入图片描述
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
  }
}

在这里插入图片描述
输入账号密码,实现简单的注册,登录功能。

  • 9
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
实现登录注册功能需要前端与后端协同工作,前端使用Vue3框架进行页面设计和交互,后端使用Spring Boot框架进行业务逻辑处理和数据存储。 以下是一个基本的登录注册功能实现流程: 1. 前端设计登录注册页面,并添表单元素和提交按钮。 2. 前端使用Vue3框架进行表单验证,确保用户输入信息的合法性。 3. 前端使用axios库发送请求到后端,请求登录或注册接口。 4. 后端使用Spring Boot框架进行接口处理,根据请求类型(登录或注册)执行相应的业务逻辑。 5. 后端使用MyBatis框架进行数据存储操作,将用户信息存储在数据库中。 6. 后端返回处理结果给前端,前端根据返回结果进行相应的提示和页面跳转。 下面是一个简单的示例代码: 前端代码: ``` <template> <div> <form> <label for="username">用户名:</label> <input type="text" id="username" v-model="username"><br> <label for="password">密码:</label> <input type="password" id="password" v-model="password"><br> <button @click.prevent="login">登录</button> <button @click.prevent="register">注册</button> </form> </div> </template> <script> import axios from 'axios'; export default { name: 'Login', data() { return { username: '', password: '' } }, methods: { login() { // 表单验证 if (!this.username || !this.password) { alert('请输入用户名和密码!'); return; } // 发送登录请求 axios.post('/api/login', { username: this.username, password: this.password }).then(res => { // 处理登录结果 if (res.data.code === 0) { alert('登录成功!'); // 跳转到首页 this.$router.push('/'); } else { alert(res.data.msg); } }).catch(err => { console.log(err); }); }, register() { // 表单验证 if (!this.username || !this.password) { alert('请输入用户名和密码!'); return; } // 发送注册请求 axios.post('/api/register', { username: this.username, password: this.password }).then(res => { // 处理注册结果 if (res.data.code === 0) { alert('注册成功!'); // 跳转到登录页 this.$router.push('/login'); } else { alert(res.data.msg); } }).catch(err => { console.log(err); }); } } } </script> ``` 后端代码: ``` @RestController @RequestMapping("/api") public class UserController { @Autowired private UserService userService; /** * 登录接口 */ @PostMapping("/login") public Result login(@RequestBody User user) { User loginUser = userService.findUserByUsername(user.getUsername()); if (loginUser == null) { return Result.error("用户名不存在!"); } else if (!loginUser.getPassword().equals(user.getPassword())) { return Result.error("密码错误!"); } else { return Result.success("登录成功!"); } } /** * 注册接口 */ @PostMapping("/register") public Result register(@RequestBody User user) { User existUser = userService.findUserByUsername(user.getUsername()); if (existUser != null) { return Result.error("用户名已存在!"); } else { userService.saveUser(user); return Result.success("注册成功!"); } } } ``` 其中,Result是一个封装了返回结果的类,可以根据需要自行设计。UserService是一个封装了用户管理相关操作的服务类,包括用户查询和添等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值