记录下最近写的东西,以后忘了还能翻翻~~
本例项目目录大概为:
前端: 后端:
前端:
准备工作:vue-cli搭建项目,安装axios,element-ui(刚开始没用element-ui所以装了bootstrap)等。
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 store from './store'
//引入element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//引入emlment-ui的提示功能
import {Message} from 'element-ui'
Vue.prototype.$message=Message
Vue.use(ElementUI);
//引入bootstrap
import 'bootstrap'
import $ from 'jquery'
// 引用axios,并设置基础URL为后端服务api地址
var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8443/api'
//登录验证用tokon
axios.defaults.withCredentials = true //请求发送cookie
// 将API方法绑定到全局
Vue.prototype.$axios = axios
Vue.config.productionTip = false
/* eslint-disable */
new Vue({
el: '#app',
router,//路由
store,//vuex
components: { App },
template: '<App/>',
emulateJSON:true,
render: h => h(App)
})
// 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(
config => {
if (window.sessionStorage.getItem('token')) {
// Vue.http.headers.common['Authorization'] = 'Bearer ' + window.sessionStorage.getItem('token')
config.headers.token = window.sessionStorage.getItem('token')
}
return config;
},
error => {
return Promise.reject(error);
});
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/login.vue'
import Welcome from '@/components/welcome.vue'
Vue.use(Router)
const router = new Router({
routes: [
//通过meta指定路由是否需要登录校验标识
{
path: '/',
redirect: '/welcome'
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path:'/welcome',
name:'Welcome',
component:Welcome
},
{
path:'/header',
name:'Header',
component: resolve => require(['@/components/commons/Header.vue'],resolve),
children:[
{
path:'/list',
name: 'List',
component:Lresolve => require(['@/components/crud/list.vue'],resolve),
},
{
path:'/add',
name: 'Add',
component:resolve => require(['@/components/crud/add.vue'],resolve),
},
{
path:'/Upload',
name:'Upload',
component: resolve => require(['@/components/views/Upload.vue'],resolve)
},
{
path:'/upList',
name:'UpList',
component: resolve => require(['@/components/views/UpList.vue'],resolve),
children:[
{
path:'/update',
name: 'Update',
component:resolve => require(['@/components/crud/update.vue'],resolve),
},
]
},
{
path:'/upFile',
name:'UpFile',
component: resolve => require(['@/components/views/UpFile.vue'],resolve)
},
{
path:'/uploadUi',
name:'UploadUi',
component: resolve => require(['@/components/views/UploadUi.vue'],resolve)
},
]
},
]
})
// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
// router.beforeEach((to, from, next) => {
// if (to.path === '/login') {
// next();
// } else {
// let token = window.sessionStorage.getItem('token');
// if (token === null || token === '') {
// next('/login');
// } else {
// next();
// }
// }
// });
export default router;
导航守卫是为了实现登录验证,但是后面为了方便,就注释了,后台也没有再验证,读者可以打开注释,后台自己添加验证代码。
登录功能:
前端 login.vue
<template>
<div>
<div class="container">
<!-- <img class="mb-4" src="../assets/img/bootstrap-solid.svg" width="72" height="72"> -->
<img src="../assets/logo.png">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<p style="color: red" >{
{Check}}</p>
<div >
<input type="text" class="form-control" placeholder="Username" v-model="loginForm.username">
</div>
<div>
<input type="password" class="form-control" placeholder="Password" v-model="loginForm.password">
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" @click="login">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</div>
</div>
</template>
<script>
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min.js'
export default {
name: 'Login',
data () {
return {
loginForm:{
username: '',
password: ''
},
responseResult: [],
Check:'',
userToken: ''
}
},
methods: {
login () {
let _this = this;
if (this.loginForm.username === '' || this.loginForm.password === '') {
alert('账号或密码不能为空');
} else {
this.$axios({
method: 'post',
url: '/login',
data: _this.loginForm
}).then(res => {
console.log(res.data);
_this.userToken = 'Bearer ' + res.data.obj;
// 将用户token保存到vuex中
window.sessionStorage .setItem('token', _this.userToken)
console.log(window.sessionStorage.getItem('token'))
_this.$router.replace({path: '/welcome'})
alert('登陆成功');
}) .catch(failResponse => {})
}
}
}
}
</script>
后端:loginController.java
package com.example.demo.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.component.TokenProccessor;
import com.example.demo.entity.Result;
import com.example.demo.entity.User;
import com.example.demo.service.LoginService;