前言php
(一).前端登陸頁面實現css
(二).後端登陸功能實現html
上一篇你們都學習到了vue前端的啓動流程,相信對於小夥伴來講都是很easy的,咱們今天主要說一下先後端分離實現登陸功能,讓咱們知道先後端分離究竟是什麼?是怎麼實現的?前端
(一).前端登陸頁面實現
vue
#登陸頁面java
前端頁面開發比較簡單,咱們這裏也不作過多的渲染,後期會作這些界面效果。
mysql
右鍵項目目錄
src\components
,操做 New -> Vue Component,命名爲 Login
內容以下:
webpack
<template><div>帳號: <input type="text" v-model="loginForm.username" placeholder="請輸入帳號"/><br><br>密碼: <input type="password" v-model="loginForm.password" placeholder="請輸入密碼"/><br><br><button v-on:click="login">登陸帳號</button></div></template>
<script>
export default {name: 'Login',data () {return {loginForm: {username: '',password: ''},responseResult: []}},methods: {login () {this.$axios.post('/login', {username: this.loginForm.username,password: this.loginForm.password}).then(succe***esponse => {if (succe***esponse.data.code === 200) {this.$router.replace({path: '/index'})} else {alert('登陸失敗!')}}).catch(failResponse => {})}}}</script>
解釋:ios
<template> 標籤中簡單的寫了一個登陸界面, methods 中定義了登陸操做,即向後端 /login 接口發送數據,得到相應成功後,頁面跳轉到 /index(成功頁面)。git
#成功主頁面HomePage.vue
<template><div>恭喜你,登陸成功啦!!!公衆號:【程序職場】 歡迎你</div></template>
<script>export default {name: 'HomePage'}</script>
<style scoped></style>
解釋:
右鍵 src\components
文件夾,新建一個 目錄 home,在 home
下新建一個 HomePage.vue
,即首頁組件。
#設置反向代理
// 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'// 設置反向代理,前端請求默認發送到 http://localhost:8082/var axios = require('axios')axios.defaults.baseURL = 'http://localhost:8082/'// 全局註冊,以後可在其餘組件中經過 this.$axios 發送數據Vue.prototype.$axios = axiosVue.config.productionTip = false
/* eslint-disable no-new */new Vue({el: '#app',router,components: { App },template: '<App/>'})
解釋:
這裏須要注意的是,使用了模塊 axios,若是沒有安裝過該模塊的,會報錯
,因此須要進入到項目文件夾中,執行 npm install --save axios
,以安裝這個模塊。
#配置頁面路由
import Vue from 'vue'import Router from 'vue-router'// 導入剛纔編寫的組件import HomePage from '@/components/home/HomePage'import Login from '@/components/Login'
Vue.use(Router)
export default new Router({routes: [// 下面都是固定的寫法{path: '/login',name: 'Login',component: Login},{path: '/index',name: 'HomePage',component: HomePage}]})
文件目錄:src\router\index.js
該內容不錯過多說明了,很簡單的操做。
#跨域支持
爲了讓後端可以訪問到前端的資源,須要配置跨域支持。
在 config\index.js
中,找到 proxyTable 位置,作跨域的支持。
'use strict'// Template version: 1.3.1// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {dev: {
// PathsassetsSubDirectory: 'static',assetsPublicPath: '/',proxyTable: {'/': {target: 'http://localhost:8082',changeOrigin: true,pathRewrite: {'^/': ''}}},// Various Dev Server settingshost: 'localhost', // can be overwritten by process.env.HOSTport: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determinedautoOpenBrowser: 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/#developmentdevtool: '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#cachebustingcacheBusting: true,
cssSourceMap: true},
build: {// Template for index.htmlindex: path.resolve(__dirname, '../dist/index.html'),
// PathsassetsRoot: path.resolve(__dirname, '../dist'),assetsSubDirectory: 'static',assetsPublicPath: '/',
/*** Source Maps*/
productionSourceMap: true,// https://webpack.js.org/configuration/devtool/#productiondevtool: '#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-pluginproductionGzip: 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 offbundleAnalyzerReport: process.env.npm_config_report}}
好了,到這裏前端頁面已經作好了,運行項目能夠看到 登陸頁面了。
執行 npm run dev
,或雙擊 dev(start 也同樣)腳本,查看登陸頁面效果。
我全部的操做都是用的 cnpm 相對比npm快。
(二).後端登陸功能實現
後端開發我是用的是 idea 首先須要新建一個項目,選擇web,mysql,jpa等 ,這裏我就不作截圖說明了,pom文件內容以下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.cxzc.mycxzc</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>demo</name><description>Demo project for Spring Boot</description>
<properties><java.version>1.8</java.version></properties>
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.40</version></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
#數據庫建立和數據添加
後端的數據庫咱們用到了mysql,首先須要咱們建立數據庫名字cxzc-vue,而後執行以下命令添加數據。
-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`username` varchar(255) DEFAULT NULL,`password` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'admin', 'admin');
#數據庫配置
server.port=8082
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/cxzc-vue?characterEncoding=UTF-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.jpa.hibernate.ddl-auto = none
#新建 User
類
package com.cxzc.mycxzc.demo.bean;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
@Entity@Table(name = "user")@JsonIgnoreProperties({"handler","hibernateLazyInitializer"})
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")int id;
String username;String password;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}}
@Entity 表示這是一個實體類
@Table(name=「user」) 表示對應的表名是 user
#數據訪問對象 UserDAO
package com.cxzc.mycxzc.demo.dao;import com.cxzc.mycxzc.demo.bean.User;import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDAO extends JpaRepository<User,Integer> {User findByUsername(String username);User getByUsernameAndPassword(String username,String password);}
Data Access Object(數據訪問對象,DAO)即用來操做數據庫的對象,這個對象能夠是咱們本身開發的,也能夠是框架提供的。這裏咱們經過繼承 JpaRepository
的方式構建 DAO。
因爲使用了 JPA,無需手動構建 SQL 語句,而只須要按照規範提供方法的名字便可實現對數據庫的增刪改查。
如 findByUsername,就是經過 username 字段查詢到對應的行,並返回給 User 類。
# UserService 數據對象的實現
package com.cxzc.mycxzc.demo.service;import com.cxzc.mycxzc.demo.bean.User;import com.cxzc.mycxzc.demo.dao.UserDAO;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserService {@AutowiredUserDAO userDAO;
public boolean isExist(String username) {User user = getByName(username);return null!=user;}
public User getByName(String username) {return userDAO.findByUsername(username);}
public User get(String username, String password){return userDAO.getByUsernameAndPassword(username, password);}
public void add(User user) {userDAO.save(user);}}
這裏是對 UserDAO 作了一次封裝,通常來說,咱們在 DAO 中只定義基礎的增刪改查操做,而具體的操做,須要由 Service 來完成。固然,因爲咱們作的操做本來就比較簡單,因此這裏看起來只是簡單地重命名了一下,好比把 「經過用戶名及密碼查詢並得到對象」 這種方法命名爲 get。
#控制器 LoginController
package com.cxzc.mycxzc.demo.controller;import com.cxzc.mycxzc.demo.bean.User;import com.cxzc.mycxzc.demo.response.Result;import com.cxzc.mycxzc.demo.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import org.springframework.web.util.HtmlUtils;
import java.util.Objects;
@Controllerpublic class LoginController {@AutowiredUserService userService;
@CrossOrigin@PostMapping(value = "/login")@ResponseBodypublic Result login(@RequestBody User requestUser) {String username = requestUser.getUsername();username = HtmlUtils.htmlEscape(username);
User user = userService.get(username, requestUser.getPassword());if (null == user) {return new Result(400);} else {return new Result(200);}}}
登陸控制器是主要控制部分,經過 UserService
提供的 get
方法查詢數據庫,若是返回的對象爲空,則驗證失敗,不然就驗證成功。
到這裏後端的開發也完成了,讓咱們 啓動後端項目,同時運行前端項目 ,訪問 http://localhost:8080/#/login,輸入用戶名 admin,密碼 admin,成功進入 localhost:8080/#/index