赞
踩
说明:这篇文章是适用于已经学过SpringBoot3和Vue3理论知识,但不会具体如何实操的过程的朋友,那么我将手把手从教大家从后端与前端交互的过程教学。
目录
一、创建一个SpringBoot3项目的和Vue3项目并进行配置
Vue创建的过程可以参考我之前写的文章
Vue 工程化项目创建快速入门这篇就够了-CSDN博客https://blog.csdn.net/qq_69183322/article/details/135747832
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/db_demo
- driver-class-name: com.mysql.cj.jdbc.Driver
- username: root
- password: 1234
-
- server:
- port: 8080
要创建utils、api、router、views文件夹
npm install axios
npm install element-plus --save
npm install vue-router@4
- import axios from "axios";
-
- const baseURL = '/api';
-
- const instance = axios.create({baseURL})
-
- instance.interceptors.response.use(
- result=>{
- return result.data;
- },
- err=>{
- alert('服务错误');
- return Promise.reject(err);
- }
-
- )
-
- export default instance;
注意:api里的js文件名和文件内容,要根据实际的接口文档写,这里先写了一个打印功能的接口,方便教学
- import request from '@/utils/request.js'
-
- export const userHelloService = ()=>{
- return request.get('/user/hello')
- }
注意:别忘记在views文件夹下创建Login.vue和Layout.vue(本次教学没用到)
- import { createRouter,createWebHistory } from "vue-router";
-
- import LoginVue from '@/views/Login.vue'
- import LayoutVue from '@/views/Layout.vue'
-
- //定义路由关系
- const routes = [
- { path:'/login',component:LoginVue},
- { path:'/',component:LayoutVue}
- ]
-
- //创建路由器
- const router = createRouter({
- history: createWebHistory(),
- routes: routes
- })
-
- export default router
- import './assets/main.css'
-
- import { createApp } from 'vue'
- import App from './App.vue'
- import router from '@/router'
- import ElementPlus from 'element-plus'
- import 'element-plus/dist/index.css'
-
- const app = createApp(App);
- app.use(router)
- app.use(ElementPlus)
- app.mount('#app')
注意:target里的url要根据后端的端口号进行修改
- import { fileURLToPath, URL } from 'node:url'
-
- import { defineConfig } from 'vite'
- import vue from '@vitejs/plugin-vue'
-
- // https://vitejs.dev/config/
- export default defineConfig({
- plugins: [
- vue(),
- ],
- resolve: {
- alias: {
- '@': fileURLToPath(new URL('./src', import.meta.url))
- }
- },
- server:{
- proxy:{
- '/api':{
- target:'http://localhost:8080',
- changeOrigin:true,
- rewrite:(path)=>path.replace(/^\/api/,'')
- }
- }
- }
- })
启动该SpringBoot项目后,通过Get方式访问locahost:8080/user/hello,就会返回"Hello World! 2024 year"字符串
- package com.example.test_demo.Controller;
-
-
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- @RequestMapping("user")
- public class UserController {
-
- @GetMapping("/hello")
- public String hello(){
- return "Hello World! 2024 year";
- }
-
-
- }
- import request from '@/utils/request.js'
-
- export const userHelloService = ()=>{
- return request.get('/user/hello')
- }
为了方便演示,我直接在App.vue(Vue.js 项目的入口文件)中输出后端传递的字符串
- <script setup>
- import {ref} from 'vue'
-
- import { userHelloService } from './api/user.js';
-
- const variable1 = ref('')
- const hello = async()=>{
- let result = await userHelloService();
- variable1.value = result
-
- }
-
- function clear(){
- variable1.value = ''
- }
- </script>
-
- <template>
- <el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
- <el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
- <h1>输出:{{variable1}}</h1>
- </template>
-
- <style scoped>
-
- </style>
点击Hello按钮时,打印后端返回的字符串"Hello World! 2024 year"
想要实现登录功能,那么在页面输入的username(用户名)和password(密码)信息要传递到后端,这样后端才能调用数据库进行验证该用户信息是否存在
- package com.example.test_demo.Controller;
-
-
- import com.example.test_demo.pojo.User;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- @RequestMapping("user")
- public class UserController {
-
- @GetMapping("/hello")
- public String hello(){
- return "Hello World! 2024 year";
- }
-
- @PostMapping("/login")
- public String login(String username,String password){
- System.out.println("用户名:"+username);
- System.out.println("密码:"+password);
-
- return "用户名:"+username+"\n密码:"+password;
- }
-
- }
- import request from '@/utils/request.js'
-
- export const userHelloService = ()=>{
- return request.get('/user/hello')
- }
-
- export const userLoginService = (loginData)=>{
- const params = new URLSearchParams();
- for(let key in loginData){
- params.append(key,loginData[key])
- }
- return request.post('/user/login',params)
- }
- <script setup>
- import {ref} from 'vue'
-
- import { userHelloService, userLoginService } from './api/user.js';
-
- const variable1 = ref('')
- const hello = async()=>{
- let result = await userHelloService();
- variable1.value = result
-
- }
-
- function clear(){
- variable1.value = ''
- }
-
-
-
- const loginData = ref({
- username: '',
- password: ''
-
- })
-
- const login = async()=>{
- let result = await userLoginService(loginData.value);
- alert(result)
-
- }
-
-
- </script>
-
- <template>
- <el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
- <el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
- <h1>输出:{{variable1}}</h1>
- <el-input v-model="loginData.username" placeholder="Please username" />
- <el-input v-model="loginData.password" placeholder="Please password" />
- <el-button type="primary" @click="login" style="margin-top:10px">登录</el-button>
- <h1>username:{{loginData.username}}</h1>
- <h1>password:{{loginData.password}}</h1>
-
- </template>
-
- <style scoped>
-
- .el-input{
- width: 200px;
- display: flex;
- justify-items: flex-start;
- }
- </style>
在页面输入用户名和密码后点击登录按钮,弹出登录用户信息后点击确认
后端显示:
可以看到后端接收到页面输入的登录信息了
我们常常需要获取单个参数进行查询或者校验,例如,我们想通过获取id来查询信息,或者获取某一类的名字来查询该类的内容,这时候就需要传递单个参数信息了
- package com.example.test_demo.Controller;
-
-
- import com.example.test_demo.pojo.User;
- import org.springframework.web.bind.annotation.*;
-
- @RestController
- @RequestMapping("user")
- public class UserController {
-
- @GetMapping("/hello")
- public String hello(){
- return "Hello World! 2024 year";
- }
-
- @PostMapping("/login")
- public String login(String username,String password){
- System.out.println("用户名:"+username);
- System.out.println("密码:"+password);
-
- return "用户名:"+username+"\n密码:"+password;
- }
-
- @DeleteMapping("/{id}")
- public String delete(@PathVariable Integer id){
- System.out.println("获取删除的id="+id);
- return "删除 id="+id+"的用户信息";
- }
- }
- import request from '@/utils/request.js'
-
- export const userHelloService = ()=>{
- return request.get('/user/hello')
- }
-
- export const userLoginService = (loginData)=>{
- const params = new URLSearchParams();
- for(let key in loginData){
- params.append(key,loginData[key])
- }
- return request.post('/user/login',params)
- }
-
- export const userDeletService = (id)=>{
- return request.delete('user/'+id)
- }
- <script setup>
- import {ref} from 'vue'
-
- import { userDeletService, userHelloService, userLoginService } from './api/user.js';
-
- const variable1 = ref('')
- const hello = async()=>{
- let result = await userHelloService();
- variable1.value = result
-
- }
-
- function clear(){
- variable1.value = ''
- }
-
-
-
- const loginData = ref({
- username: '',
- password: ''
-
- })
-
- const login = async()=>{
- let result = await userLoginService(loginData.value);
-
- }
-
- const id = ref()
- const deleteById = async()=>{
- let result = await userDeletService(id.value);
- id.value = result
- }
-
-
- </script>
-
- <template>
- <el-button type="default" @click="hello" style="margin-top:10px">Hello</el-button>
- <el-button type="primary" @click="clear" style="margin-top:10px">清空</el-button>
- <h1>输出:{{variable1}}</h1>
- <el-input v-model="loginData.username" placeholder="Please username" />
- <el-input v-model="loginData.password" placeholder="Please password" />
- <el-button type="primary" @click="login" style="margin-top:10px">登录</el-button>
- <h1>username:{{loginData.username}}</h1>
- <h1>password:{{loginData.password}}</h1>
- 输入删除的ID:<el-input v-model="id" placeholder="Please deleteId" />
- <el-button type="danger" @click="deleteById" style="margin-top:10px">删除</el-button>
- <h1>deleteById:{{id}}</h1>
-
- </template>
-
- <style scoped>
-
- .el-input{
- width: 200px;
- display: flex;
- justify-items: flex-start;
- }
- </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。