前后端分离web项目

过程

1.构建前端

使用到的工具:
  • 套件工具-用来安装依赖
    • yarn(此篇文章选用)
    • npm
  • 前端构建工具:
    • webpack
    • vite(此篇文章选用)
    • nuxt.js
  • 前端框架
    • Vue(此篇文章选用)
    • react
  • 前端语言
    • typescript
    • javascript(此篇文章选用)
  • 前端渲染框架
    • semidesign-不支持vue
    • Element ui(此篇文章选用)
步骤:

1.安装yarn,使用yarn构建web项目的前端部分。
在使用yarn时可能会碰到一个问题:无法加载文件 C:\Users\28011\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本

解决方案为:
 (1)搜索powershell, 右键以管理员身份运行。
 (2)执行set-ExecutionPolicy RemoteSigned,将计算机上的 执行策略更改为 RemoteSigned

解决这个问题之后,就可以使用vite来生成前端的项目了。
具体操作见Vite官方文档。
https://cn.vitejs.dev/guide/#scaffolding-your-first-vite-project
运行成功之后会显示:
运行成功
访问生成的链接。
2.在vscode中打开刚才yarn生成的项目,根据你的需求,更改项目的配置。
此处以在项目中配置css渲染框架Element ui为例,来说明如何按需配置。
(1)首先根据Element官方给出的文档,安装Element。
安装Element
(2)再按需导入所要使用的插件。

使用自动导入的方式:

首先你需要安装unplugin-vue-components 和 unplugin-auto-import这两款插件

npm install -D unplugin-vue-components unplugin-auto-import

然后把下列代码插入到你的 Vite 或 Webpack 的配置文件中

Vite

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default {
  plugins: [
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
}

(3)完成上述步骤之后,你就可以去Element中找到你心仪的组件并把相应的代码copy到你想要的位置即可。

2.构建后端

按照spring项目的传统编写方式,写完bean、mapper、service、controller等之后。使用postman模拟前端向后端发送请求。
  • 在controller中要用ResponseBody来接受前端发来的请求体。
@PostMapping("/login")
    public Object login(@RequestBody User user) {
        System.out.println(user.getUsername());
        User user1 = userService.findByUsername(user.getUsername());
        LoginResponse loginResponse = new LoginResponse();
        if (user1 == null) {
            loginResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
            loginResponse.setMessage("User not exist");
            return new ResponseEntity(loginResponse, HttpStatus.BAD_REQUEST);
        } else if (!user1.getPassword().equals(user.getPassword())) {
            loginResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
            loginResponse.setMessage("User password error");
            return new ResponseEntity(loginResponse, HttpStatus.BAD_REQUEST);
        }
        loginResponse.setMessage("Login success");
        loginResponse.setToken("123");
        loginResponse.setHttpStatus(HttpStatus.OK);
        return loginResponse;
    }
}
  • 前端向后端发送请求时,因为域名的不同,涉及到跨域问题。请求会发送失败。此时需要在后端中新建一个config文件,在其中新建一个WebConfig.java文件,在文件中写入:就可以解决跨域访问问题了。
package com.example.demo_backend.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}
  • 后端响应前端的请求,我们需要新建一个response文件夹,在文件夹下新建一个LoginResponse.class文件,保存响应前端login请求的信息。
package com.example.demo_backend.response;

import org.springframework.http.HttpStatus;

public class LoginResponse {
//主要是这三个信息,作为响应返回前端
    private String message;
    private String token;
    private HttpStatus httpStatus;

    public LoginResponse() {
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    public void setHttpStatus(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }
}
  • 此时回头查看第一条,就会发现我们在controller的方法中将loginResponse返回到了前端。
  • 此处顺便提一下,mapper的注解式写法,我把代码放在这里,应该很容易看懂。
package com.example.demo_backend.mapper;

import com.example.demo_backend.bean.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {
    @Insert("insert into User (id, email, tel, username, password) values (#{id}, #{email}, #{tel}, #{username}, #{password})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    Boolean insertUser(User user);

    @Select("select * from User where username=#{username}")
    User findUserByUsername(String username);
}

到此,后端的所有应该清晰了起来。
目录结构

3.前后端连接

1.配置“Vue-router”(路由),使通过连接跳转至相应的网页(纯前端问题)。
  • 使用yarn add vue-router 指令下载Vue-router依赖。
  • 在全局的配置文件main.js中配置vue-router。
 import router from './router'

//此处要格外注意代码先后顺序的问题,否则就会导致vue-rooter加载异常
 const app = createApp(App)
 app.use(router)
 app.mount('#app')
  • 创建一个新的文件夹router,在这个文件夹下面新建一个index.js文件,用来配置页面跳转。
  • (此处假设你已经编写好了相关的需要跳转的页面),然后就可以去配置Index.js中的页面跳转了。
import { createRouter, createWebHistory } from "vue-router";

const routes = [
//这里放配置页面跳转的代码,path是访问的路径,component指向相应要跳转的页面。
    {
        path: "/",
        name: "Home",
        component: () => import("../views/Home.vue"),
    },
    {
        path: "/login",
        name: "Login",
        component: () => import("../views/Login.vue"),
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});
export default router;
2.配置axios, 实现前端向后端的请求。
  • 使用yarn add axios下载依赖。
  • 在全局配置文件main.js中配置axios。
import axios from 'axios'

//这里写后端的端口号
axios.defaults.baseURL = "http://127.0.0.1:8080"
  • 在需要向后端发送请求的页面中导入axios,并且编写向后端发送请求的代码。
<script>

import { reactive } from "vue"
import axios from "axios"
import { ElMessage } from "element-plus"

 const onSubmit = () => {
            console.log("submit");
            //向后端发送请求,并且等待接受后端返回的回应。
            return axios.post("/user/login", form).then(res=>{
                console.log(res.data);
                ElMessage({
                    message: res.data.message,
                    type:'success'
                });
            }).catch(e => {
                ElMessage.error(e.response.data)
            })
  • 注意,使用yarn生成项目之后,默认App.vue是前端界面的入口。要在App.vue界面中加入。就可以正常跳转了。
<template>
<!-- 整個頁面的入口 -->
<router-view />

</template>
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值