Sky Takeaway (1) The most suitable Java practice project for novices Springboot+SSM project "Sky Takeaway" project actual combat, notes (super detailed, novice) [continuous update]

Project address https://gitee.com/zhang-zakcomy/cang-qiong-take-out/

1. Environment construction - Day01 project overview, environment construction

Overall Introduction to Software Development

software development process

image.png

  1. demand analysis

Completion of requirement specification and product prototype
writing Requirement specification generally uses Word documents to describe each component of the current project, such as: system definition, application environment, functional specifications, performance requirements, etc., will be described in the document.
Product prototypes generally show what kind of data the current page displays in the form of web pages (html), what the layout of the page looks like, click on a certain menu, what page to open, click on a certain button, and what effect appears. See through product prototypes.

  1. design

The content of the design includes UI design, database design, and interface design.

  1. UI design: the design of the user interface, the page effect of the main design project, as small as a button, as large as a page layout, and the embodiment of human-computer interaction logic.
  2. Database design: It is necessary to design which databases are involved in the current project, which tables are contained in each database, what is the relationship between these table structures, and which fields are contained in the table structure.
  3. Interface design: By analyzing the prototype diagram, firstly, analyze how many interfaces each page has in a coarse-grained manner, and then analyze the incoming parameters and return value parameters of each interface in a fine-grained manner, and clarify the interface path and request method at the same time.

An interface is equivalent to a certain protocol, which allows different components or modules to better communicate with each other and work together in software or project design

  1. Coding: This stage is mainly to realize each module and function of the software and write specific codes according to the design documents. At this stage, you need to pay attention to the quality and readability of the code, and at the same time, you need to follow the coding norms and standards to ensure the reliability and maintainability of the code.
  2. Testing: This stage is mainly to test the compiled program, verify whether the program meets the requirements and design requirements, and discover and fix possible defects and loopholes at the same time. At this stage, detailed test plans and test cases need to be developed, and various possible scenarios and situations need to be considered to ensure the quality and stability of the program.
  3. On-line operation and maintenance: This stage is mainly to deploy the program to the production environment for actual operation and maintenance. At this stage, it is necessary to formulate a reasonable deployment plan and operation and maintenance plan. At the same time, it is necessary to monitor the status and operation of the program in real time, and to detect and deal with possible problems and failures in time.

Role division

After being familiar with the entire software development process, we also need to understand the job roles involved in the entire software development process and the division of responsibilities of each role.

position/role corresponding stage The division of responsibilities
project manager all stages Responsible for the entire project, assigning tasks and controlling progress
product manager demand analysis Conduct demand research, output demand research documents, product prototypes, etc.
UI designer design Output interface renderings based on product prototypes
architect design Overall project architecture design, technology selection, etc.
Development Engineer coding Function code implementation
Test Engineer test Write test cases and output test reports
Operation and Maintenance Engineer Online operation and maintenance Build the software environment and launch the project

In actual projects, some project teams may not have dedicated architects or testers due to tight staffing. At this time, project managers or programmers may be required to act concurrently.

Software Environment

As a software development engineer, you will inevitably come into contact with a variety of software environments during the coding process. We mainly analyze the three sets of environments that you often encounter in your work, namely: development environment, test environment, and production environment. Next, we introduce the functions and characteristics of these three environments.
1). Development environment (development)
As a software developer, the environment used in the development stage is the development environment, which is generally inaccessible to external users.
For example, the MySQL database and other common software we use in development can be installed locally or on a dedicated server. These application software are only used in the software development process, when the project is tested and launched , we will not use this environment anymore, this environment is the development environment.
2). Testing environment (testing)
As a software development engineer, after developing the functional modules of the project and passing the unit test, the project needs to be deployed to the test server for testers to test the project. Then this test server is an environment specially used by testers, that is, the test environment, which is used for project testing and generally cannot be accessed by external users.
3). Production environment (production)
When the project is developed and passed the test by the testers, the project can be launched, deployed to the online environment, and officially provided external services. This online environment is also called the production environment. .

First of all, project development will be carried out in the development environment. Often the development environment is mostly the local computer environment and the environment in the LAN. After the development is completed, the project will be deployed to the test environment. The test environment is generally an independent test environment The server environment, after the project test passes, finally deploy the project to the production environment. The production environment can be an online environment such as a computer room or a cloud server.

Sky takeaway project introduction

Project Introduction

This project (Kongqiong Takeout) is a software product specially customized for catering enterprises (restaurants, restaurants), including two parts: the system management background and the small program terminal application. Among them, the system management background is mainly provided for the internal staff of catering enterprises. It can manage and maintain the classification, dishes, set menus, orders, employees, etc. of restaurants, and can perform statistics on various data of restaurants. The mini program terminal is mainly provided to consumers, who can browse dishes online, add shopping carts, place orders, pay, and remind orders, etc.
image.png

product prototype

The product prototype is used to demonstrate the business functions of the project and is generally designed by the product manager.
Note: The product prototype is mainly used to demonstrate the function of the project, not the final page effect.
Under the product prototype folder of the "data" folder, two product prototypes are provided.
image.png
1). The management terminal
is used by internal employees of catering companies. The main functions are:

module describe
login/logout Internal employees must log in before they can access the system management background
employee management Administrators can manage employee information in the background of the system, including query, add, edit, disable and other functions
Category management It mainly manages and maintains the classification of dishes or set meals operated by the current restaurant, including functions such as query, addition, modification, and deletion
Dishes management Mainly maintain the dish information under each category, including query, add, modify, delete, start selling, stop selling, etc.
package management Mainly maintain the package information in the current restaurant, including query, add, modify, delete, start selling, stop selling, etc.
order management Mainly maintain the order information placed by the user on the mobile terminal, including functions such as inquiry, cancellation, delivery, completion, and order report download
Statistics Mainly complete various statistics of restaurants, such as turnover, number of users, orders, etc.

2). Client side
Mobile applications are mainly provided for consumers. The main functions are:

module describe
login/logout Users need to log in and use the mini program to order food after authorization through WeChat
order-menu In the ordering interface, it is necessary to display the category of dishes/sets, and load the information of the dishes according to the currently selected category for users to query and choose
order-shopping cart The dishes selected by the user will be added to the user's shopping cart, which mainly includes functions such as querying the shopping cart, adding to the shopping cart, deleting the shopping cart, and emptying the shopping cart.
s After the user selects the dishes/sets, he can settle and pay for the dishes in the shopping cart, and then he needs to pay for the order
personal information The basic information of the current user will be displayed on the personal center page, the user can manage the delivery address, and can also query historical order data

Technology selection

image.png
1). User layer
In this project, we will use H5, Vue.js, ElementUI, apache echarts (chart display) and other technologies to build the front-end page of the system management background. When building mobile applications, we will use WeChat applets.
2). Gateway layer
Nginx is a server, which is mainly used as an Http server to deploy static resources and has high access performance. There are two more important functions in Nginx: reverse proxy and load balancing. During project deployment, to achieve Tomcat load balancing, it can be achieved through Nginx.
3). Application layer
SpringBoot: Quickly build Spring projects, adopt the idea of ​​"convention is better than configuration", and simplify the configuration and development of Spring projects.
SpringMVC: SpringMVC is a module of the spring framework. Springmvc and spring do not need to be integrated through an intermediate integration layer and can be seamlessly integrated.
Spring Task: Timing task framework provided by Spring.
httpclient: It mainly realizes the sending of http requests.
Spring Cache: A data caching framework provided by Spring
JWT: A token used to authenticate users on an application.
Alibaba Cloud OSS: Object storage service, which mainly stores files, such as pictures, in the project.
Swagger: It can automatically help developers generate interface documents and test the interfaces.
POI: Encapsulates common operations on Excel tables.
WebSocket: A communication network protocol that simplifies the data exchange between the client and the server, and is used to realize the functions of order receipt and reminder for the project.
4). Data layer
MySQL: Relational database, the core business data of this project will be stored in MySQL.
Redis: An in-memory database based on key-value format storage, with fast access speed, and it is often used as a cache.
Mybatis: The persistence layer of this project will be developed using Mybatis.
pagehelper: pagination plugin.
spring data redis: API that simplifies java code to operate Redis.
5). Tool
git: version control tool, in team collaboration, use this tool to manage the code in the project.
maven: project build tool.
junit: a unit testing tool. After the developer's functions are implemented, they need to unit test the functions through junit.
postman: An interface testing tool that simulates various HTTP requests initiated by users and obtains corresponding response results.

Build the development environment

Front-end environment construction

  1. Front-end engineering based on nginx

In "Information":
image.png
it will be image.pngplaced in a folder with no Chinese in the directory address, named "CangqiongTakeout"image.png

Be sure to put this folder in the directory with Chinese characters, otherwise the startup will not succeed

  1. Start nginx, access test

Double-click nginx.exethe qidong nginx service, the access port number is 80
http://localhost:80
If the startup is successful, the interface is as follows:
image.png

Back-end environment construction

Familiar with the project structure

The back-end project is based on maven for project creation and sub-module development

  1. Find the backend initial project from "Data"

image.png

  1. Copy the initial project to the "CangqiongTakeout" directory just created

image.png
Open the initial project with IDEA to understand the project structure


If the project does not have a generated .imlfile, the following settings need to be made:

  1. Open the terminal in idea under this project

image.png

  1. .Enter the corresponding module, enter the mvn idea:module command, press Enter
  2. After BUILD SUCCESS, you can see that the .iml file is generated under the corresponding module

image.png


After setup, the initial project structure is as follows
image.png


Description of the role of each module of the project:

serial number name illustrate
1 sky-take-out Maven parent project, unified management of dependency versions, aggregation of other submodules
2 sky-common Sub-module, storing public classes, such as tool classes, constant classes, exception classes, etc.
3 sky-pojo Sub-module, storing entity classes, VO, DTO, etc.
4 sky-server Sub-modules, back-end services, store configuration files, Controller, Service, Mapper, etc.

After understanding the overall structure of the project, each of the above sub-modules will be analyzed in detail:

  • sky-common: 模块中存放的是一些公共类,可以供其他模块使用 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BAv4c5lv-1690964505677)(assets/image-20221107093606590.png#id=cHOSd&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)]
    | 名称 | 说明 |
    | — | — |
    | constant | 存放相关常量类 |
    | context | 存放上下文类 |
    | enumeration | 项目的枚举类存储 |
    | exception | 存放自定义异常类 |
    | json | 处理json转换的类 |
    | properties | 存放SpringBoot相关的配置属性类 |
    | result | 返回结果类的封装 |
    | utils | 常用工具类 |

  • sky-pojo: 模块中存放的是一些 entity、DTO、VO [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bCSk9iUm-1690964505677)(assets/image-20221107094611987.png#id=UKsvk&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)]
    | 名称 | 说明 |
    | — | — |
    | Entity | 实体,通常和数据库中的表对应 |
    | DTO | 数据传输对象,通常用于程序中各层之间传递数据 |
    | VO | 视图对象,为前端展示数据提供的对象 |
    | POJO | 普通Java对象,只有属性和对应的getter和setter |

  • sky-server: 模块中存放的是 配置文件、配置类、拦截器、controller、service、mapper、启动类等 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dV8g7ErE-1690964505677)(assets/image-20221107094852361.png#id=z1ASu&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)]
    | 名称 | 说明 |
    | — | — |
    | config | 存放配置类 |
    | controller | 存放controller类 |
    | interceptor | 存放拦截器类 |
    | mapper | 存放mapper接口 |
    | service | 存放service类 |
    | SkyApplication | 启动类 |

git版本控制

使用Git进行项目代码的版本控制,具体操作:

  1. 创建git仓库

image.pngimage.png
当IDEA中出现image.png时创建成功

  1. 创建git远程仓库

登录链接gitee.com,新建仓库
image.pngimage.png
点击“创建”后如下图:
image.png

  1. 提交文件至本地仓库

image.png
开始提交:
点击此处image.png
image.pngimage.png

  1. 添加至git远程仓库
  • 复制远程地址

image.png

  • 点击此处image.png

image.pngimage.png
推送完成
刷新gitee页面:
image.png

数据库环境搭建

image.png
将数据库中sky.sql文件导入MySQL,间脚本代码复制到MySQL运行即可
创建出11张表
image.png
image.png
修改idea后端代码 的数据库 的配置信息

前后端联调

后端的初始工程中已经实现了登录功能,直接进行前后端联调测试即可

意思就是,在后端已经有了登录功能的代码了,前端也有了页面实现的代码了,现在需要将前后端联结起来

image.png


首先,先编译一下,能够保证项目能够正常运行
image.png
image.png
登录一下:
双击nginx.exeqidong nginx服务,访问端口号为80
http://localhost:80

要保证前面数据库idea中将相关配置信息根据实际情况配制成自己数据库的信息

image.png
点击登录:
image.png

右上角的“错误”先不用管,后面会解决

nginx反向代理和负载均衡

对登录功能测试完毕后,接下来,思考一个问题:前端发送的请求,是如何请求到后端服务的?
在使用Nginx作为反向代理的Java项目中,前端发送的请求会被Nginx接收并处理,然后转发给后端服务。以下是一些基本步骤:

  1. 客户端(前端)发送请求到Nginx服务器。
  2. Nginx服务器接收请求,并根据配置的规则进行处理。
  3. Nginx根据配置的规则将请求转发给后端服务。
  4. 后端服务接收到请求并处理,然后返回响应。
  5. Nginx接收后端服务的响应,并将其返回给客户端。

在这个过程中,Nginx扮演了反向代理的角色,接收客户端的请求并转发给后端服务,同时也将后端服务的响应返回给客户端。通过Nginx,可以实现对请求的负载均衡、缓存、安全过滤等处理,提高系统的性能和安全性。


当你在浏览器中输入一个网站地址并发送请求时,这个请求首先会被Nginx服务器接收。Nginx服务器会根据你发送的请求类型、请求头、参数等来进行处理,然后决定将请求转发给哪个后端服务。这个后端服务可以是应用程序服务器、数据库服务器或其他类型的服务。
一旦后端服务接收到请求并处理完成,它会将响应返回给Nginx服务器。Nginx服务器再将这些响应返回给你所在的浏览器。在这个过程中,Nginx还可以对请求和响应进行一些处理,例如提供缓存功能、防止DDoS攻击、拦截恶意请求等,从而提高系统的性能和安全性。

在实际情况中,前端请求地址和后端接口地址通常是不一致的,这是因为前端通常只需要知道如何将请求发送到后端,而不需要知道后端的具体实现细节,包括端口、上下文路径等。

在nginx服务器中,可以通过配置反向代理来实现前后端请求的映射。具体来说,可以在nginx配置文件中添加以下配置:

location /api {
    proxy_pass http://localhost:8080/admin;
}

这样,当有请求发送到nginx服务器的/api路径时,nginx会将请求转发到后端服务器的/admin路径。
在SpringBoot项目中,也可以使用Spring Cloud Gateway等反向代理框架来实现前后端请求的映射。例如,可以配置Spring Cloud Gateway的路由规则,将/api/_路由到后端服务器的/admin/_路径。
总之,无论使用nginx还是Spring Cloud Gateway等反向代理框架,都可以实现前后端请求的映射,使得前端请求能够正确地请求到后端服务。

导入接口文档

接下来,就要进入到项目的业务开发了,而我们的开发方式就是基于当前企业主流的前后端分离开发方式,那么这种方式就要求我们之前需要先将接口定义好,这样前后端人员才能并行开发,所以,这个章节就需要将接口文档导入到管理平台,为我们后面业务开发做好准备。其实,在真实的企业开发中,接口设计过程其实是一个非常漫长的过程,可能需要多次开会讨论调整,甚至在开发的过程中才会发现某些接口定义还需要再调整,这种情况其实是非常常见的,但是由于项目时间原因,所以选择一次性导入所有的接口,在开发业务功能过程当中,也会带着大家一起来分析一下对应的接口是怎么确定下来的,为什么要这样定义,从而培养同学们的接口设计能力。

前后端分离开发流程

第一步:定义接口,确定接口的路径、请求方式、传入参数、返回参数。
第二步:前端开发人员和后端开发人员并行开发,同时,也可自测。
第三步:前后端人员进行连调测试。
第四步:提交给测试人员进行最终测试

操作步骤

  1. 找到“资料”中的接口文件

image.png

  1. 导入到Yapi平台

登录Yapi
image.png
image.pngimage.png
image.png
两个操作步骤相同

Swagger

介绍

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务(https://swagger.io/)。 它的主要作用是:

  1. 使得前后端分离开发更加方便,有利于团队协作
  2. 接口的文档在线自动生成,降低后端开发人员编写接口文档的负担
  3. 功能测试
    Spring已经将Swagger纳入自身的标准,建立了Spring-swagger项目,现在叫Springfox。通过在项目中引入Springfox ,即可非常简单快捷的使用Swagger。

knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,前身是swagger-bootstrap-ui,取名kni4j是希望它能像一把匕首一样小巧,轻量,并且功能强悍!
目前,一般都使用knife4j框架。

使用步骤

  1. 导入 knife4j 的maven坐标
    在pom.xml中添加依赖
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
  1. 在配置类中加入 knife4j 相关配置
    WebMvcConfiguration.java
/**
     * 通过knife4j生成接口文档
     * @return
*/
    @Bean
    public Docket docket() {
    
    
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
  1. 设置静态资源映射,否则接口文档页面无法访问
    WebMvcConfiguration.java
/**
     * 设置静态资源映射
     * @param registry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
  1. 访问测试
    接口文档访问路径为 http://ip:port/doc.html —> http://localhost:8080/doc.html

image.pngimage.png
**思考:**通过 Swagger 就可以生成接口文档,那么我们就不需要 Yapi 了?
1、Yapi 是设计阶段使用的工具,管理和维护接口
2、Swagger 在开发阶段使用的框架,帮助后端开发人员做后端的接口测试

常用注解

通过注解可以控制生成的接口文档,使接口文档拥有更好的可读性,常用注解如下:

注解 说明
@Api 用在类上,例如Controller,表示对类的说明
@ApiModel 用在类上,例如entity、DTO、VO
@ApiModelProperty 用在属性上,描述属性信息
@ApiOperation 用在方法上,例如Controller的方法,说明方法的用途、作用

Next, use the above annotations to modify the original code as follows: Generate a more readable interface document in EmployeeLoginDTO.java
in the sky-pojo module

package com.sky.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
@ApiModel(description = "员工登录时传递的数据模型")
public class EmployeeLoginDTO implements Serializable {
    
    

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("密码")
    private String password;

}

EmployeeLoginVo.java

package com.sky.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "员工登录返回的数据格式")
public class EmployeeLoginVO implements Serializable {
    
    

    @ApiModelProperty("主键值")
    private Long id;

    @ApiModelProperty("用户名")
    private String userName;

    @ApiModelProperty("姓名")
    private String name;

    @ApiModelProperty("jwt令牌")
    private String token;

}

In sky-server module
EmployeeController.java

package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {
    
    

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) 	{
    
    
        //..............

        
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("员工退出")
    public Result<String> logout() {
    
    
        return Result.success();
    }

}

Start the service: visit http://localhost:8080/doc.html
image.png

one o'clock two o'clock

  1. This project started as the so-called "initial project" of the directly imported dark horse programmers
    1. It is to realize the framework, dependencies, configuration, etc. for you
  2. Follow the video tutorial process to complete this project first
    1. Some places may not be suitable for chewing and understanding, but gulping
    2. Maybe when the whole project is completed, some parts will be understood naturally
    3. There may be some places that I don’t understand after completing this project, but I will understand after completing this project
  3. To stop at the completion of a project or a certain stage in a project
    1. See if you can chew what you swallowed whole now

Guess you like

Origin blog.csdn.net/qq_64744030/article/details/132009782