当前位置:   article > 正文

SpringBoot后台开发基础Demo_springboot 后端demo

springboot 后端demo

**

SpringBoot后台开发基础

**
Project FlashSale

什么是SSM?

一个整合SSM框架的高并发和商品秒杀项目,学习目前较流行的Java框架组合实现高并发秒杀API

项目来源

项目来自于国内IT公开课平台慕课网,很适合学习一些技术的基础。这个项目是教你快速使用SpringBoot搭建好一个秒杀电商网站。

在这里插入图片描述
首先我们需要复习一个基本知识
什么是OOP?

还需要了解两个个进阶知识
什么是AOP?
什么是MVC?什么是SpringMVC?

相信当你做完这个教程后能对以下这几个问题能有一些自己的看法

为什么要使用MVC的开发模式?为什么会出现MVP?
OOP和MVC的关系
为什么使用框架开发?为什么会出现SpringCloud?
云开发有什么优势?

一、使用SpringBoot完成基础项目搭建

使用IDEA创建Maven项目

File->New->Project->Maven(如图)
或者可以直接使用Spring Initializer直接初始化(怎么做?)
在这里插入图片描述
选择后填写必须的GroupId以及ArtifactId

什么是GroupId和ArtifactId?
在这里插入图片描述
设置IDEA设置以及jar包下载路径
在这里插入图片描述
项目命名以及本地项目地址
在这里插入图片描述
项目创建完成
在这里插入图片描述

二、SpringBoot

官方文档

SpringBoot.io
SpringBoot-Github

第三方QA和教学

SpringBoot-StackOverflow
SpringBoot-知乎
在这里插入图片描述
打开pom.xml添加SpringBoot依赖,这里推荐有条件的同学翻墙下载,速度会快一些并且少很多warning
(ctrl cv就行,这个项目基本够用,有需要以后自己加)

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

@RequestMapping
@ResponseBody
@RequestParam

如何使用SpringBoot基于RESTful搭建简单web服务?

三,Mybatis

什么是Mybatis?
为了使用Mybatis,我们需要添加以下依赖(如果直接ctrl cv之前的依赖现在则不用添加)

   <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
   		</dependency>
   <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

依赖后在resource目录下建立命名为application.properties的空文件(file)
在这里插入图片描述
命名必须是application.properties
在这里插入图片描述
配置application.properties

#设置Tomcat端口,默认8080,可以在1025-65534中任意修改
server.port=8080
#设置项目ContextPath
#server.servlet.context-path=/axsc
#设置Spring boot编码
spring.banner.charset=UTF-8
#设置Tomcat编码
server.tomcat.uri-encoding=UTF-8
##########################################################
#数据库配置
#数据库连接地址
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8

#这一段非常重要,解决时区不同步等一系列问题
#useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8

#数据库用户名和密码
spring.datasource.username=root
spring.datasource.password=qwer1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#配置.xml文件路径
mybatis.mapper-locations=classpath:/mapping/*.xml
logging.level.com.flashsale.project.dao = debug
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

配置完application.properties之后需要添加Mybatis Generator插件

<plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.5</version>
        <configuration>
            <!--mybatis的代码生成器的配置文件-->
            <!--允许覆盖生成的文件-->
            <verbose>true</verbose>
            <overwrite>true</overwrite>
        </configuration>
    </plugin>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

添加完插件后我们需要对插件配置
首先在resource目录下添加GeneratorConfig.xml
在这里插入图片描述
然后将下面的代码改成自己的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
	<!--masqlconnector jar包地址-->
	<!--这里要改-->
    <!--<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->
    <classPathEntry location="C:\Users\ChenSJ\.m2\repository\mysql\mysql-connector-java\8.0.20\mysql-connector-java-8.0.20.jar"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--数据库连接地址账号密码-->
        <!--这里要改-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/user?serverTimezone=GMT%2B8"
                        userId="root"
                        password="qwer1234">
        </jdbcConnection>

        <!--生成Model/DataObject类存放的位置-->
        <!--这里要改-->
        <javaModelGenerator targetPackage="com.flashsale.project.dataobject" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--生成映射文件存放的位置-->
        <!--可改可不改-->
        <sqlMapGenerator targetPackage="mapping"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--生成Dao类存放的位置-->
        <!--可改可不改-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.flashsale.project.dao"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName = "user_info" domainObjectName = "UserDO">
        </table>

        
<!--        这段代码可以避免生成不常用方法-->
<!--        enableCountByExample="false"enableUpdateByExample="false"-->
<!--        enableDeleteByExample="false"enableSelectByExample="false"selectByExampleQueryId="false"-->

        <table tableName = "user_account" domainObjectName = "UserAccountDO"></table>

    </context>
</generatorConfiguration>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

配置完成后开始设计数据库
这里推荐使用ERWin(教程)设计数据库而不是使用sql语句直接构造

注意,此处表的命名必须和MybatisConfig中完全一致

<table tableName = "user_info" domainObjectName = "UserDO">
  • 1

表user_account
在这里插入图片描述
表user_info
在这里插入图片描述
配置完成后在右侧Maven选项中找到mybatis-generator:generate双击运行即可生成需要的文件
在这里插入图片描述
MybatisGenerator生成结果
在这里插入图片描述
我们接下来在UserController类中加入以下方法

    @Autowired
    private UserService service;
    
	@RequestMapping("/get")
    @ResponseBody
    public UserDO getUser(@RequestParam(name = "id") Integer id)
    {
        return service.getUserById(id);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

新建一个package命名为service并添加接口文件命名为UserService
在这里插入图片描述
添加以下代码

public interface UserService
{
    UserDO getUserById(Integer id);
}
  • 1
  • 2
  • 3
  • 4

再新建一个java类命名为UserServiceImplementation
在这里插入图片描述
什么是@Service,@Autowired?
添加以下代码

package com.flashsale.project.service.implementation.implementation;

@Service
public class UserServiceImplement implements UserService{

    @Autowired(required = false)
    private UserDOMapper userDOMapper;

    @Autowired(required = false)
    private UserAccountDOMapper userAccountDOMapper;

    @Override
    public UserDO getUserById(Integer id){
        UserDO userDO = userDOMapper.selectByPrimaryKey(id);
        UserAccountDO userAccountDO = userAccountDOMapper.selectByPrimaryKey(userDO.getId());

        return userDO;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

运行程序
打开任意浏览器输入

http://localhost:8080/[#设置的的mapping id]/get?[#设置的输入值名]=[#自己设置的值]
#例
http://localhost:8080/user/get?id=1
  • 1
  • 2
  • 3

即可返回数据库数据

{"id":1,"name":"admin","gender":1,"age":25,"telphone":"12345678901","registerMode":"1","thirdPartyId":"1"}
  • 1

四,简易异常处理

首先复习一下Java异常捕获和处理
这个是本地数据库表user_info中添加的记录,可以看到字段id只有1
在这里插入图片描述
假如我们访问id=2的get方法

http://localhost:8080/user/get?id=2
  • 1

很明显,如果没有值取到会造成空指针并崩溃
在这里插入图片描述
在这里插入图片描述
现在为了避免这个问题我们需要添加一个简单的异常处理流程
首先先创建一个命名为errorimpl的package
在这里插入图片描述
在errorimpl里新建接口CommonError
在这里插入图片描述
填写以下代码

public interface CommonError {
    public int getErrCode();
    public String getErrMsg();
    public CommonError setErrMsg(String errMsg);
}
  • 1
  • 2
  • 3
  • 4
  • 5

新建一个Enum类
如何理解Enum?
在这里插入图片描述
添加以下代码

public enum EmBusinessError implements CommonError {

    PARAMETER_VALIDATION_ERROR(00001,"参数不合法"),
    USER_NOT_EXIST(10001,"用户不存在")
    ;

    private EmBusinessError(int errCode, String errMsg){
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    private int errCode;
    private String errMsg;


    @Override
    public int getErrCode() {
        return this.errCode;
    }

    @Override
    public String getErrMsg() {
        return this.errMsg;
    }

    @Override
    public CommonError setErrMsg(String errMsg) {
        this.errMsg = errMsg;
        return this;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

最后新建Java类

public class BussinessException extends Exception implements CommonError{
    private CommonError commonError;

    //直接接收EmBusinessError的传参用于构造业务异常
    public BussinessException(CommonError commonError){
        super();
        this.commonError = commonError;
    }

    //接受自定义errMsg的方式构造业务异常
    public BussinessException(CommonError commonError, String errMsg){
        super();
        this.commonError = commonError;
        this.commonError.setErrMsg(errMsg);
    }

    @Override
    public int getErrCode() {
        return this.commonError.getErrCode();
    }

    @Override
    public String getErrMsg() {
        return this.commonError.getErrMsg();
    }

    @Override
    public CommonError setErrMsg(String errMsg) {
        this.commonError.setErrMsg(errMsg);
        return this;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

添加完后在UserController类中修改get方法

   @RequestMapping("/get")
    @ResponseBody
    public UserDO getUser(@RequestParam(name = "id") Integer id) throws BussinessException {
        if(service.getUserById(id)==null)
        {
        //抛出异常
            throw new BussinessException(EmBusinessError.USER_NOT_EXIST);
        }else {
            return service.getUserById(id);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

然后就不崩溃了
但是请注意,throwException仅仅只做到了抛出异常,意味着这个错误只被发现但未被处理。这里推荐使用try catch捕获异常,但try catch需要被放在controller(业务逻辑层)而不是其他层
throw,throws,try catch区别

五,getotp验证

首先先创建一个package命名为response
添加一个类命名为CommonReturnType并添加以下代码

package com.flashsale.project.response;

import lombok.Data;

@Data
public class CommonReturnType {
    //表明对应请求的返回处理结果“success”或“fail"
    private String status;

    //若status=success,则data内返回前端需要的json数据
    //若status=fail,则data内使用通用的错误码格式
    private Object data;

    //定义一个通用的创建方法
    public static CommonReturnType create(Object result) {
        return CommonReturnType.create(result,"success");

    }
    public static CommonReturnType create(Object result,String status) {
        CommonReturnType type = new CommonReturnType();
        type.setStatus(status);
        type.setData(result);
        return type;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

在UserController类中添加以下方法

@Autowired
    private HttpServletRequest httpServletRequest;

@RequestMapping("/getotp")
    @ResponseBody
    //otp验证
    public CommonReturnType getOtp(@RequestParam(name="telephone")String telephone){
        Random rand = new Random();
        int randint=rand.nextInt(99999);
        randint += 10000;
        String otpCode = String.valueOf(randint);

        //绑定otp验证码到对应手机
        httpServletRequest.getSession().setAttribute(telephone,otpCode);

        //发送otp验证码到用户
        System.out.println("telephone = "+telephone+"&otpCode"+otpCode);

        return CommonReturnType.create(null);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

打开浏览器
输入

http://localhost:[设置的端口号]/[方法名]?[字段名]=[字段内容]
#例
http://localhost:8080/user/getotp?telephone=12345678901
  • 1
  • 2
  • 3

在控制台中即可接收到数据

telephone = 12345678901&otpCode26107
  • 1

在这里插入图片描述
至此,你已经完成了一个基于SpringBoot的后台开发任务

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/966930
推荐阅读
相关标签
  

闽ICP备14008679号