1. 程式人生 > 程式設計 >基於SpringBoot構建電商秒殺專案程式碼例項

基於SpringBoot構建電商秒殺專案程式碼例項

一、專案功能概述

電商秒殺需要完成的3個功能:

1.展示一個商品列表頁面,我們可以從中看到可秒殺的商品列表

2.點選進入商品詳情頁,獲取該商品的詳細資訊

3.秒殺時間開始後,點選進入下單確認頁面,並支付成功

二、基於SpringBoot進行專案環境搭建

步驟1:建立一個maven工程,使用quickStart骨架。

步驟2:在pom.xml匯入SpringBoot相關依賴。

 <?xml version="1.0" encoding="UTF-8"?>
 
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion> 
  <groupId>org.example</groupId>
  <artifactId>Spike</artifactId>
  <version>1.0-SNAPSHOT</version>
 
  <name>Spike</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url> 
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.5.RELEASE</version>
 </parent> 
  <properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <maven.compiler.source>1.8</maven.compiler.source>   <maven.compiler.target>1.8</maven.compiler.target>
  </properties> 
  <dependencies>
   <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
   <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
   </dependency>
  </dependencies> 
  <build>
   <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    <plugins>
     <!-- clean lifecycle,see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
     <plugin>
     <artifactId>maven-clean-plugin</artifactId>
      <version>3.1.0</version>
     </plugin>
     <!-- default lifecycle,jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
     <plugin>
      <artifactId>maven-resources-plugin</artifactId>
      <version>3.0.2</version>
     </plugin>
     <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.0</version>
     </plugin>
     <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.22.1</version>
     </plugin>
     <plugin>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.0.2</version>
     </plugin>
     <plugin>
      <artifactId>maven-install-plugin</artifactId>
      <version>2.5.2</version>
    </plugin>
     <plugin>
      <artifactId>maven-deploy-plugin</artifactId>
      <version>2.8.2</version>
     </plugin>
     <!-- site lifecycle,see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
     <plugin>
      <artifactId>maven-site-plugin</artifactId>
      <version>3.7.1</version>
     </plugin>
     <plugin>
      <artifactId>maven-project-info-reports-plugin</artifactId>
      <version>3.0.0</version>
     </plugin>
    </plugins>
   </pluginManagement>
  </build>
 </project>

步驟3:在main/java/app中,我們對SpringBoot和SpringMVC進行簡單的配置工作。掌握這幾個註解的作用。

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//SpringBoot會幫我們啟動tomcat,並載入預設配置
@EnableAutoConfiguration
//SpringMVC相關配置
@RestController
public class App {
  @RequestMapping("/")
  public String home(){
    //網頁中輸出
    return "Hello World!";
  }
  public static void main( String[] args ){
    //控制檯輸出
    System.out.println( "Hello World!" );
    SpringApplication.run(App.class,args);
  }
}

執行結果:

用瀏覽器開啟http://localhost:8080/,我們可以看到頁面上輸出:Hello World!

同時,控制檯也輸出了Hello World!,以及一些Spring相關的資訊。

SpringBoot小技巧:可以在resource目錄下建立一個application.propeties配置檔案,在其中寫:server.port = 埠號來設定埠號。

步驟4:接入mybatis,首先在pom.xml新增需要的依賴(mysql,druid連線池,mybatis)

寫一個plugin標籤,引入對應的mybatis自動生成檔案的外掛 {

新增對應的依賴:mybatis generator的core(第一次使用要單獨在前面匯入依賴,不可直接放在plugin中),mysql資料庫的解析

寫一個excution標籤:設定允許移動生成的檔案,允許自動覆蓋檔案(實際工作中不可以)

寫一個configuration標籤:指定mybatis generator 配置檔案的路徑 }

1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5  <modelVersion>4.0.0</modelVersion>
 6 
 7  <groupId>org.example</groupId>
 8  <artifactId>Spike</artifactId>
 9  <version>1.0-SNAPSHOT</version>
 10 
 11  <name>Spike</name>
 12  <!-- FIXME change it to the project's website -->
 13  <url>http://www.example.com</url>
 14 
 15 <parent>
 16  <groupId>org.springframework.boot</groupId>
 17  <artifactId>spring-boot-starter-parent</artifactId>
 18  <version>2.0.5.RELEASE</version>
 19 </parent>
 20 
 21  <properties>
 22   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 23   <maven.compiler.source>1.8</maven.compiler.source>
 24   <maven.compiler.target>1.8</maven.compiler.target>
 25  </properties>
 26 
 27  <dependencies>
 28   <dependency>
 29    <groupId>org.springframework.boot</groupId>
 30    <artifactId>spring-boot-starter-web</artifactId>
 31   </dependency>
 32   <dependency>
 33    <groupId>mysql</groupId>
 34    <artifactId>mysql-connector-java</artifactId>
 35    <version>5.1.6</version>
 36   </dependency>
 37   <dependency>
 38    <groupId>com.alibaba</groupId>
 39    <artifactId>druid</artifactId>
 40    <version>1.1.3</version>
 41   </dependency>
 42   <dependency>
 43    <groupId>org.mybatis.spring.boot</groupId>
 44    <artifactId>mybatis-spring-boot-starter</artifactId>
 45    <version>1.3.1</version>
 46   </dependency>
 47   <dependency>
 48    <groupId>junit</groupId>
 49    <artifactId>junit</artifactId>
 50    <version>4.11</version>
 51    <scope>test</scope>
 52   </dependency>
 53   <dependency>
 54    <groupId>org.mybatis.generator</groupId>
 55    <artifactId>mybatis-generator-core</artifactId>
 56    <version>1.3.5</version>
 57   </dependency>
 58  </dependencies>
 59 
 60  <build>
 61   <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
 62    <plugins>
 63     <!-- clean lifecycle,see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
 64     <plugin>
 65      <artifactId>maven-clean-plugin</artifactId>
 66      <version>3.1.0</version>
 67     </plugin>
 68     <!-- default lifecycle,jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
 69     <plugin>
 70      <artifactId>maven-resources-plugin</artifactId>
 71      <version>3.0.2</version>
 72     </plugin>
 73     <plugin>
 74      <artifactId>maven-compiler-plugin</artifactId>
 75      <version>3.8.0</version>
 76     </plugin>
 77     <plugin>
 78      <artifactId>maven-surefire-plugin</artifactId>
 79      <version>2.22.1</version>
 80     </plugin>
 81     <plugin>
 82      <artifactId>maven-jar-plugin</artifactId>
 83      <version>3.0.2</version>
 84     </plugin>
 85     <plugin>
 86      <artifactId>maven-install-plugin</artifactId>
 87      <version>2.5.2</version>
 88     </plugin>
 89     <plugin>
 90      <artifactId>maven-deploy-plugin</artifactId>
 91      <version>2.8.2</version>
 92     </plugin>
 93 
 94     <!-- site lifecycle,see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
 95     <plugin>
 96      <artifactId>maven-site-plugin</artifactId>
 97      <version>3.7.1</version>
 98     </plugin>
 99     <plugin>
100      <artifactId>maven-project-info-reports-plugin</artifactId>
101      <version>3.0.0</version>
102     </plugin>
103 
104     <plugin>
105      <groupId>org.mybatis.generator</groupId>
106      <artifactId>mybatis-generator-maven-plugin</artifactId>
107      <version>1.3.5</version>
108      <dependencies>
109       <dependency>
110        <groupId>org.mybatis.generator</groupId>
111        <artifactId>mybatis-generator-core</artifactId>
112        <version>1.3.5</version>
113       </dependency>
114       <dependency>
115        <groupId>mysql</groupId>
116        <artifactId>mysql-connector-java</artifactId>
117        <version>5.1.6</version>
118       </dependency>
119      </dependencies>
120      <executions>
121       <execution>
122        <id>mybatis generator</id>
123        <phase>package</phase>
124        <goals>
125         <goal>generate</goal>
126        </goals>
127       </execution>
128      </executions>
129      <configuration>
130       <!--允許移動生成的檔案-->
131       <verbose>true</verbose>
132       <!--允許自動覆蓋檔案-->
133       <overwrite>true</overwrite>
134       <!--mybatis generator 配置檔案的路徑-->
135       <configurationFile>
136        src/main/resource/mybatis-generator.xml
137       </configurationFile>
138      </configuration>
139     </plugin>
140 
141    </plugins>
142   </pluginManagement>
143  </build>
144 </project>

步驟5:建立mysql底層的資料庫與相關表格

1.建立資料庫spike

2.建立一個user_info表格

基於SpringBoot構建電商秒殺專案程式碼例項

3.建立一個user_password表格,並設定user_id為外來鍵關聯user_info的id

基於SpringBoot構建電商秒殺專案程式碼例項

步驟6:在步驟4中,我們最後指定了mybatis generator 配置檔案的路徑,於是我們在指定路徑(resource目錄下)建立一個mybatis generator.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>
  <context id="mysql" targetRuntime="MyBatis3" >
    <!--資料庫連線地址賬號密碼-->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/spike" userId="root" password="0322">
    </jdbcConnection>
    <!--生成Data Object類存放位置-->
    <javaModelGenerator targetPackage="org.example.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 targetPackage="org.example.dao" type="XMLMAPPER" targetProject="src/main/java">
      <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>
    <!--生成對應表及類名-->
    <table tableName="user_info" domainObjectName="UserDo" enableCountByExample="false"
        enableUpdateByExample="false" enableDeleteByExample="false"
        enableSelectByExample="false" selectByExampleQueryId="false"
    ></table>
    <table tableName="user_password" domainObjectName="UserPasswordDO" enableCountByExample="false"
        enableUpdateByExample="false" enableDeleteByExample="false"
        enableSelectByExample="false" selectByExampleQueryId="false"
    ></table>
  </context>
</generatorConfiguration>

步驟7:根據步驟6中指定的位置,我們在org.example目錄下新建一個dataobject的包,一個dao包。並測試是否能夠成功生成相應的檔案:

run——edit configurations——+maven——command line:mybatis-generator:generate——apply

然後我們執行這個新建的命令,可以看到resources/mapping下多了兩個檔案:

基於SpringBoot構建電商秒殺專案程式碼例項

dataobject包與dao包下生成了如下檔案:

基於SpringBoot構建電商秒殺專案程式碼例項

手動刪除兩個Example檔案。

步驟8:為了接入mybatis對應mysql的資料來源,我們繼續編寫application.properties檔案

 server.port = 8090
 mybatis.mapperLocations = classpath:mapping/*.xml
 
 spring.datasource.name = Spike
 spring.datasource.url = jdbc:mysql://127.0.0.1:3306/Spike
 spring.datasource.username = root
 spring.datasource.password = 0322
 
 #使用druid資料來源
 spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
 spring.datasource.driverClassName = com.mysql.jdbc.Driver

步驟9:回到app.java

將@EnableAutoConfiguration註解改為@SpringBootApplication(scanBasePackages = "org.example"),作用是將app交給spring託管,並且指定為主啟動類。

添加註解@MapperScan("org.example.dao"),把dao存放的地方設定在對應註解下面。

最後,寫一個方法來測試我們的搭建工作是否完成,(事先在表格中新增一條資料)

 package org.example; 
 import org.example.dao.UserDoMapper;
 import org.example.dataobject.UserDo;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 //SpringBoot會幫我們啟動tomcat,並載入預設配置
 @SpringBootApplication(scanBasePackages = {"org.example"})
 
 //SpringMVC相關配置
 @RestController
 @MapperScan("org.example.dao")
 public class App {
   @Autowired
   private UserDoMapper userDoMapper;
 
   @RequestMapping("/")
   public String home(){
     UserDo userDo = userDoMapper.selectByPrimaryKey(1);
     if(userDo == null){
      return "使用者物件不存在";
     }else{
       return userDo.getName();
     } 
   }
   public static void main( String[] args ){
     //控制檯輸出
     System.out.println( "Hello World!" );
     SpringApplication.run(App.class,args);
   }
 }
app.java

開啟http://localhost:8090/,我們可以看到頁面上顯示了我們新增的資料中name欄位的內容。

三、使用者模組開發

1.使用SpingMVC模式開發使用者資訊

步驟1:補全框架結構:

基於SpringBoot構建電商秒殺專案程式碼例項

步驟2:service層的編寫:

UserService介面:

package org.example.service;
import org.example.service.model.UserModel;
public interface UserService {
  UserModel getUserById(Integer id);
}

UserService實現類:

@Service
public class UserServiceImpl implements UserService {
  @Autowired
  private UserDoMapper userDoMapper;

  @Autowired
  private UserPasswordDOMapper userPasswordDOMapper;

  @Override
  public UserModel getUserById(Integer id) {
    UserDo userDo = userDoMapper.selectByPrimaryKey(id);
    if(userDo == null){
      return null;
    }
    //通過使用者id獲取對應的使用者加密密碼資訊
    UserPasswordDO userPasswordDO = userPasswordDOMapper.selectByUserId(userDo.getId());
    return convertFromDataObject(userDo,userPasswordDO);
  }

  public UserModel convertFromDataObject(UserDo userDo,UserPasswordDO userPasswordDO) {
    if(userDo == null){
      return null;
    }
    UserModel userModel = new UserModel();
    BeanUtils.copyProperties(userDo,userModel);
    if(userPasswordDO != null){
      userModel.setEncriptPassword(userPasswordDO.getEncriptPassword());
    }
    return userModel;
  }
}

UserModel類:存放資料庫的所有對應欄位與getters&setters,用於service層與資料庫資料的解耦,使service層無法直接接觸資料庫

1 package org.example.service.model;
 2 
 3 public class UserModel {
 4   private Integer id;
 5   private String name;
 6   private Byte gender;
 7   private Integer age;
 8   private String telephone;
 9   private String registerMode;
10   private String thirdPartyId;
11   private String encriptPassword;
12 
13   public Integer getId() {
14     return id;
15   }
16 
17   public void setId(Integer id) {
18     this.id = id;
19   }
20 
21   public String getName() {
22     return name;
23   }
24 
25   public void setName(String name) {
26     this.name = name;
27   }
28 
29   public Byte getGender() {
30     return gender;
31   }
32 
33   public void setGender(Byte gender) {
34     this.gender = gender;
35   }
36 
37   public Integer getAge() {
38     return age;
39   }
40 
41   public void setAge(Integer age) {
42     this.age = age;
43   }
44 
45   public String getTelephone() {
46     return telephone;
47   }
48 
49   public void setTelephone(String telephone) {
50     this.telephone = telephone;
51   }
52 
53   public String getRegisterMode() {
54     return registerMode;
55   }
56 
57   public void setRegisterMode(String registerMode) {
58     this.registerMode = registerMode;
59   }
60 
61   public String getThirdPartyId() {
62     return thirdPartyId;
63   }
64 
65   public void setThirdPartyId(String thirdPartyId) {
66     this.thirdPartyId = thirdPartyId;
67   }
68 
69   public String getEncriptPassword() {
70     return encriptPassword;
71   }
72 
73   public void setEncriptPassword(String encriptPassword) {
74     this.encriptPassword = encriptPassword;
75   }
76 }

步驟3:修改UserPasswordDOMapper.xml,新增一個selectByUserId操作的配置

<select id="selectByUserId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from user_password
  where user_id = #{userId,jdbcType=INTEGER}
 </select>

同步修改UserPasswordDOMapper.java,新增一行程式碼:

UserPasswordDO selectByUserId(Integer userId);

步驟4:編寫Controller包中的UserController.java

@Controller("user")
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserService userService;
  @RequestMapping("/get")
  @ResponseBody
  public UserModel getUser(@RequestParam(name="id") Integer id) {
    //呼叫service服務獲取對應id的使用者物件並返回給前端
    UserModel userModel = userService.getUserById(id);
    return userModel;
  }
}

執行後,訪問http://localhost:8090/user/get?id=1(需要事先新增好一條完整的資料),可以看到頁面上輸出了這條資料的完整資訊。

步驟5:發現問題:在UserController中,我們把userModel模型直接返回給前端,導致密碼直接輸出在頁面中,這是非常不專業的。

因此,我們在controller層(包)中需要新建一個模型物件。在controller層中新建一個viewobject包,並在其中寫一個viewobject類,裡面只寫需要展示在前端的欄位與getters&setters。

1 package org.example.controller.viewobject;
 2 
 3 public class UserVO {
 4   //只寫前端使用者所需要的資訊
 5   private Integer id;
 6   private String name;
 7   private Byte gender;
 8   private Integer age;
 9   private String telephone;
10 
11   public Integer getId() {
12     return id;
13   }
14 
15   public void setId(Integer id) {
16     this.id = id;
17   }
18 
19   public String getName() {
20     return name;
21   }
22 
23   public void setName(String name) {
24     this.name = name;
25   }
26 
27   public Byte getGender() {
28     return gender;
29   }
30 
31   public void setGender(Byte gender) {
32     this.gender = gender;
33   }
34 
35   public Integer getAge() {
36     return age;
37   }
38 
39   public void setAge(Integer age) {
40     this.age = age;
41   }
42 
43   public String getTelephone() {
44     return telephone;
45   }
46 
47   public void setTelephone(String telephone) {
48     this.telephone = telephone;
49   }
50 }

同時,我們修改UserController類,將UserModel轉化為viewobject後,再返回給前端。

@Controller("user")
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserService userService;
  @RequestMapping("/get")
  @ResponseBody
  public UserVO getUser(@RequestParam(name="id") Integer id) {
    //呼叫service服務獲取對應id的使用者物件並返回給前端
    UserModel userModel = userService.getUserById(id);
    //將核心領域模型物件轉化為可供UI使用的viewobject
    return convertFromModel(userModel);
  }
  private UserVO convertFromModel(UserModel userModel){
    if(userModel == null){
      return null;
    }
    UserVO userVO = new UserVO();
    BeanUtils.copyProperties(userModel,userVO);
    return userVO;
  }
}

這一步中,我們做了一個完整的從資料庫中讀取資料,展示在前端頁面上的操作。

controller層——>service層——>dao層

dataobject層負責資料儲存到service的傳輸,並且在使用者的service的服務中組裝了對應的核心領域模型。

controller層做了到使用者viewobject之間的傳遞,保證密碼等資訊不會輸出到前端。

2.定義通用的返回物件

步驟1:自主管理前端頁面的返回——返回正確資訊

org.example包下建立一個response包,在其中建立一個CommonReturnType.java檔案。

在該檔案中,設定兩個屬性:status,data,並生成對應的getters&setters。然後寫兩個構造方法,包含了兩個屬性的設定。

 package org.example.response;
 
 public class CommonReturnType {
   //表名對應請求的返回處理結果,success/fail
   private String status;
   //若status返回success,則data內返回前端需要的json資料
   //若status返回success,則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;
   }
 }

修改我們的UserController.java,將返回值改為CommonReturnType,由CommonReturnType呼叫create方法來引用UserVO中的資訊。以下程式碼為需要修改的部分:

public CommonReturnType getUser(@RequestParam(name="id") Integer id) {
    //呼叫service服務獲取對應id的使用者物件並返回給前端
    UserModel userModel = userService.getUserById(id);
    //將核心領域模型物件轉化為可供UI使用的viewobject
    UserVO userVO = convertFromModel(userModel);
    //返回通用物件
    return CommonReturnType.create(userVO);
  }

執行後,我們仍然訪問http://localhost:8090/user/get?id=1,可以看到頁面上輸出了:

基於SpringBoot構建電商秒殺專案程式碼例項

步驟2:自主管理前端頁面的返回——返回錯誤資訊

org.example包下建立一個error包,在其中建立一個CommonError介面,寫3個方法:獲取錯誤碼,獲取錯誤資訊,設定錯誤資訊

 public interface CommonError {
   public int getErrCode();
   public String getErrMsg();
   public CommonError setErrMsg(String errMsg);
 }

error包下寫一個列舉型別的EmBusinessError,實現CommonError介面。

package org.example.error;

public enum EmBusinessError implements CommonError{
  //通用錯誤型別10001
  PARAMETER_VALIDATION_ERROR(10001,"引數不合法"),//未知錯誤10002
  UNKNOWN_ERROR(10002,"未知錯誤"),//20000開頭相關為使用者資訊相關錯誤定義
  USER_NOT_EXIST(20001,"使用者不存在"),;

  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;
  }
}

error包下寫一個BusinessException,實現CommonError介面,並繼承Exception類。

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

  //直接接收EmBusinessError的傳參用於構造業務異常
  public BusinessException(CommonError commonError) {
    super();
    this.commonError = commonError;
  }

  public BusinessException(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;
  }
}

UserController中新增如下程式碼:

   //若獲取的對應使用者資訊不存在
     if(userModel==null){
       throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
     }

步驟3:異常處理

在controller目錄下單獨寫一個BaseController類,定義exceptionhandler解決未被controller層吸收的exception。

import java.util.Map;

public class BaseController {
  //定義exceptionhandler解決未被controller層吸收的exception
  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.OK)
  @ResponseBody
  public Object handlerException(HttpServletRequest request,Exception ex){
    Map<String,Object> responseData = new HashMap<>();
    if(ex instanceof BusinessException){
      BusinessException businessException = (BusinessException)ex;
      responseData.put("errCode",businessException.getErrCode());
      responseData.put("errMsg",businessException.getErrMsg());
    }else{
      responseData.put("errCode",EmBusinessError.UNKNOWN_ERROR.getErrCode());
      responseData.put("errMsg",EmBusinessError.UNKNOWN_ERROR.getErrMsg());

    }
    return CommonReturnType.create(responseData,"fail");
  }
}

然後,UserController類需要繼承BaseController類。

執行後,我們訪問http://localhost:8090/user/get?id=2,(id=2的資料是不存在的),可以看到頁面為:

基於SpringBoot構建電商秒殺專案程式碼例項

為了程式的健壯性,我們在BaseController中添加了一個unknown error。我們可以手動地來測試一下這段程式碼是否起了作用:

修改UserController部分程式碼如下:

    if(userModel==null){
       userModel.setEncriptPassword("123");
       //throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
     }

執行後,我們再次訪問http://localhost:8090/user/get?id=2,可以看到頁面為:

基於SpringBoot構建電商秒殺專案程式碼例項

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。