Vue+SpringBoot(一)简单登录界面的实现

您所在的位置:网站首页 springboot与前端vue交互 Vue+SpringBoot(一)简单登录界面的实现

Vue+SpringBoot(一)简单登录界面的实现

2023-09-04 01:24| 来源: 网络整理| 查看: 265

【SpringBoot总结】历史文章 SpringBoot总结(一)——第一个SpringBoot项目 SpringBoot总结(二)——Spring Boot的自动配置 SpringBoot总结(三)——SpringBoot的配置文件 SpringBoot总结(四)——@Value和@ConfigurationProperties的区别 SpringBoot总结(五)——@PropertySource注解与@ImportResource注解 SpringBoot总结(六)——SpringBoot配置文件占位符 SpringBoot总结(七)——Profile的使用 SpringBoot总结(八)——配置文件的加载位置 SpringBoot总结(九)——@Conditional注解与自动配置报告 SpringBoot总结(十)——SpringBoot+Mybatis实现数据库的CRUD(从创建到实现【超详细附代码】) SpringBoot总结(十一)——SpringBoot的静态资源映射规则 SpringBoot总结(十二)——登录界面的实现

Vue+SpringBoot简单登录界面的实现

文章目录 Vue+SpringBoot简单登录界面的实现前言一、创建Vue项目1.1、安装node.js 二、页面实现三、页面路由的配置四、运行项目五、后端的实现5.1、创建实体5.2、创建结果集5.3、创建Controller5.4、创建Service5.5、创建数据库访问DAO5.6、配置文件5.7、解决跨域问题 六、运行效果总结

前言 在[SpringBoot总结(十二)——登录界面的实现]这篇文章中使用了thymeleaf模板引擎,实现了登录操作;本篇文章将会用Vue+SpringBoot实现一个简单的Demo,包括登录界面、注册、以及修改密码的功能,(页面有点丑);后端使用了SpringBoot与Mybatis整合的方式操作数据库。

开发工具及环境:HBuilderX、 IDEA、Maven、jdk1.8、Mysql、

一、创建Vue项目

Vue的脚手架是依赖于node.js,因此我们要先安装node.js。

1.1、安装node.js

从node.js官网node.js官网下载nodejs,安装过程很简单,一直Next即可。 在这里插入图片描述 (1)安装完成后,用下面命令检查安装是否成功(出现版本号,则安装成功);同样的npm(node.js的包管理工具)会自动安装上。同样输入npm -v 查看版本。

node -v npm -v

在这里插入图片描述 (2)使用淘宝NPM 镜像

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

(3)安装vue-cli(全局安装vue-cli)

cnpm install vue-cli -g

(4)初始化项目

vue init webpack +项目名

(5)启动项目 用cd命令进入项目目录,用npm install 安装项目所需依赖,npm run dev启动项目即可。

二、页面实现

登录界面 Login.vue

用户名: 密码: 登录 账号注册 修改密码 import Cookies from 'js-cookie'; export default { name: 'Login', data() { return { userName: "", password: "", } }, created() { }, methods: { login: function() { let fd = new FormData(); fd.append("userName", this.userName); fd.append("passwd", this.password); // console.log(fd.get("passwd")); let config = { headers: { 'Content-Type': 'multipart/form-data' } } this.$axios.post("user/login", fd, config).then(res => { alert(res.data.msg) if (res.data.code === 200) { Cookies.set('userName', fd.get('userName')); this.$router.push({ path: '/success' }) } else { } }).catch(res => { alert(res.data.msg) }) } } }

注册页面 Register.vue

用户名: 密码: 确认密码: 注册 现在登录 export default { name: 'Register', data() { return { userName: "", userName: "", password2: "" } }, created() { }, methods: { register: function() { let fd = new FormData(); fd.append("userName", this.userName); fd.append("passwd", this.password); let config = { headers: { 'Content-Type': 'multipart/form-data' } } if (this.password === this.password2) { this.$axios.post("user/register", fd, config).then(res => { alert(res.data.msg) if (res.data.code === 200) { // 回到登录界面 this.$router.push({ path: '/' }) } }).catch(res => { alert(res.data.msg) }) } else { alert("两次输入的密码不同") } } } }

修改密码页面 ChangePwd.vue

当前登录的用户是:{{ LoginuserName }} 用户名: 原密码: 新密码: 确认新密码: 确定修改 import Cookies from 'js-cookie'; export default { name: 'ChangePwd', data() { return { oldpassword: "", newpassword: "", newpassword2: "" } }, created() { }, computed: { LoginuserName() { return Cookies.get('userName'); } }, methods: { ChangePwd: function() { let fd = new FormData(); fd.append("username", this.LoginuserName); fd.append("oldpassword", this.oldpassword); fd.append("newpassword", this.newpassword); let config = { headers: { 'Content-Type': 'multipart/form-data' } } if (this.oldpassword.length === 0 || this.newpassword.length === 0 || this.newpassword2.length === 0) { alert("密码不能为空"); return; } else if (this.newpassword === this.newpassword2) { this.$axios.post("user/changepwd", fd, config).then(res => { alert(res.data.msg) if (res.data.code === 200) { // 回到登录界面 this.$router.push({ path: '/' }) } }).catch(res => { alert(res.data.msg); }) } else { alert("两次输入的新密码不同") } } } }

成功页面 Success.vue

欢迎你 {{ username }}登录成功! 返回登录界面 import Cookies from 'js-cookie'; export default{ computed:{ username(){ return Cookies.get('userName'); } } } 三、页面路由的配置

src\router\index.js

import Vue from 'vue' import Router from 'vue-router' import Register from '@/components/Register' import Login from '@/components/Login' import Success from '@/components/Success' import ChangePwd from '@/components/ChangePwd' Vue.use(Router) export default new Router({ // 修改为History路由模式 mode: 'history', routes: [ { path: '/', name: '登录', component: Login }, { path: '/Register', name: '注册', component: Register }, { path: '/Success', name: '登录成功', component: Success }, { path: '/ChangePwd', name: '修改密码', component: ChangePwd }, ] })

将路由添加到程序入口,设置反向代理:修改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 axios from 'axios' var axios = require('axios') axios.defaults.baseURL = 'http://localhost:8002'; Vue.prototype.HOST='/user' Vue.prototype.$axios = axios Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, //调用组件 template: '' }) 四、运行项目

cd 切换到项目的根路径,执行 npm run dev 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

五、后端的实现

关于详细的SpringBoot与Mybatis整合步骤:SpringBoot总结(十)——SpringBoot+Mybatis实现数据库的CRUD(从创建到实现【超详细附代码】) 这里只展示主要的实现代码。

5.1、创建实体 package com.example.demo.entity; public class User { private Integer userId; private String userName; private String passwd; private String status; private String registTime; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getRegistTime() { return registTime; } public void setRegistTime(String registTime) { this.registTime = registTime; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", passwd='" + passwd + '\'' + ", status='" + status + '\'' + ", registTime='" + registTime + '\'' + '}'; } } 5.2、创建结果集 package com.example.demo.core; public class Result { private int code; private String msg; private Object data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } 5.3、创建Controller

UserContrloller.java

@Api(description = "用户接口") @RestController @RequestMapping("/user") @CrossOrigin public class UserController { @Autowired private UserService userService; @ApiOperation(value = "用户注册", notes = "用户注册") @RequestMapping(value = "/register", method = RequestMethod.POST) @CrossOrigin public Result register(@RequestParam String userName, @RequestParam String passwd) { Result result = new Result(); if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passwd)) { result.setMsg("用户名和密码不能为空"); return result; } // 验证用户名是否已经注册 User exsitUser = userService.selectByName(userName); if (exsitUser != null) { result.setMsg("该用户名已存在"); return result; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(new Date()); User user = new User(); user.setUserName(userName); user.setRegistTime(format); user.setStatus("1"); user.setPasswd(Md5Util.MD5(passwd) ); int count = userService.insert(user); System.out.println(count); if (count != 1) { result.setMsg("注册失败"); return result; } result.setMsg("注册成功"); result.setCode(200); return result; } @ApiOperation(value = "用户登录", notes = "用户登录") @RequestMapping(value = "/login", method = RequestMethod.POST) @CrossOrigin public Result login(@RequestParam String userName, @RequestParam String passwd, HttpSession session, HttpServletResponse response) { Result result = new Result(); User exsitUser = userService.selectByName(userName); if (exsitUser == null) { result.setMsg("该用户未注册"); result.setCode(400); return result; } if (!exsitUser.getPasswd().equals(Md5Util.MD5(passwd))) { result.setMsg("密码错误,请重新输入"); result.setCode(400); return result; } session.setAttribute("username", userName); result.setCode(200); result.setMsg("登录成功"); return result; } @RequestMapping(value = "/changepwd", method = RequestMethod.POST) @CrossOrigin public Result changepwd(@RequestParam String username,@RequestParam String oldpassword,@RequestParam String newpassword, HttpSession session) { Result result = new Result(); User exsitUser = userService.selectByName(username); if (!Md5Util.MD5(oldpassword).equals(exsitUser.getPasswd())) { System.out.println(oldpassword); result.setMsg("原密码输入错误"); return result; }else { int count = userService.updatePwd(username, Md5Util.MD5(newpassword)); if (count>0) { result.setMsg("密码修改成功"); result.setCode(200); return result; } result.setMsg("密码修改错误"); return result; } } } 5.4、创建Service

UserService.java

package com.example.demo.service; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired public UserMapper userMapper; public User selectByName(String userName){ return userMapper.getUserByName(userName); } public int insert(User user){ return userMapper.addUser(user); } public int updatePwd(String username,String newpassword) { return userMapper.updateUser(username,newpassword); } } 5.5、创建数据库访问DAO

UserMapper.java

package com.example.demo.mapper; import com.example.demo.entity.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; /** * */ @Mapper public interface UserMapper { @Select("select * from t_user where userName = #{userName}") public User getUserByName(String userName); @Insert("insert into t_user (userName,passwd,status,registTime) values (#{userName}, #{passwd}, #{status}, #{registTime})") public int addUser(User user); @Update("update t_user set passwd = #{newpassword} where userName = #{username}") public int updateUser(String username, String newpassword); } 5.6、配置文件 server.port=8002 spring.datasource.url=jdbc:mysql://localhost:3306/vue?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=123 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 5.7、解决跨域问题

这里使用的是用配置类的方式。也可以在后端相关Controller添加跨域注解@CrossOrigin实现。

package com.example.demo.config; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CrosConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } } 六、运行效果

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

总结

用一个十分简陋的界面,实现了登录、注册、修改密码的功能,希望能给予大家帮助。😊

下一篇:Vue+SpringBoot(二)实现后台获取数据在前台显示



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3