SpringBoot 2.0實戰專車系列一:開發Restful Web應用

實戰專車系列教程使用的 SpringBoot 版本為 2.1.6.RELEASE,所有實戰示例都會經過嚴格測試,如果因版本問題導致錯誤,請自行 Google 或者諮詢。

專車介紹

該趟專車是開往 SpringBoot Restful Web 應用的實戰專車,主要講解如何快速搭建一個 Restful 風格的 Web 應用

專車問題

第一個問題:如何使用 SpringBoot 快速搭建一個 Web 應用?

第二個問題:如何讓 SpringBoot 接收和響應的 json 數據字段是下劃線風格而不是駝峰式風格?

專車實戰

首先在 Idea 中創建一個名為 boot-example 的 project,作為整個項目的父模塊,然後在其下面創建一個名為 boot-example-web 的子模塊

在父模塊中添加管理依賴

<code><properties>
\t<spring.boot.version>2.1.6.RELEASE/<spring.boot.version>
\t<lombok.version>1.16.10/<lombok.version>
/<properties>

<dependencymanagement>
<dependencies>
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-dependencies/<artifactid>
<version>${spring.boot.version}/<version>
<type>pom/<type>
<scope>import/<scope>
/<dependency>

<dependency>
<groupid>org.projectlombok/<groupid>
<artifactid>lombok/<artifactid>
<version>${lombok.version}/<version>

/<dependency>
/<dependencies>
/<dependencymanagement>/<code>

在子模塊中添加需要的依賴

<code><dependencies>
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-web/<artifactid>
/<dependency>

<dependency>
<groupid>org.projectlombok/<groupid>
<artifactid>lombok/<artifactid>
/<dependency>
/<dependencies>/<code>

依賴添加完成之後就可以開始愉快的編寫代碼了

第一步:既然開發一個 web 應用,那麼必然要啟動該 web 服務,毫無疑問,我們需要創建一個啟動類

<code>@SpringBootApplication
public class WebApplication {

public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}/<code>

啟動類很簡單,第一點需要在我們的啟動類上添加@SpringBootApplication 註解,來標註這是一個 SpringBoot 應用,第二點調用 SpringApplication.run 方法來啟動 SpringBoot 應用。該方法是整個 SpringBoot 的核心,裡面做了很多的初始化工作,後續有機會來具體分析下 SpringBoot 的啟動原理。

第二步:創建一個 Restful 風格的控制器

<code>@RestController
@RequestMapping("/students")
public class StudentController {

private static List<student> studentList = new ArrayList<>();

static {
studentList.add(new Student(100001, "jack", 22));
studentList.add(new Student(100002, "lucky", 23));
studentList.add(new Student(100003, "jone", 24));
studentList.add(new Student(100004, "lucy", 25));
studentList.add(new Student(100005, "lily", 26));
}

@GetMapping("/")
public List<student> listStudent() {
return studentList;
}

@GetMapping("id/{id}")
public Student getStudent(@PathVariable("id") Integer id) {
return studentList.stream()
.filter(student -> Objects.equals(student.getId(), id))
.findFirst()
.orElse(new Student(999999, "default", 18));
}

@PostMapping("/")
public List<student> addStudent(@RequestBody Student student) {
studentList.add(student);
return studentList;
}

@PutMapping("/")
public List<student> updateStudent(@RequestBody Student student) {
studentList.removeIf(stu -> Objects.equals(stu.getId(), student.getId()));
studentList.add(student);
return studentList;
}
}/<student>/<student>/<student>/<student>/<code>

控制器也很簡單,第一點要在類上使用@RestController 和@RequestMapping 註解,@RestController 表示當前控制器中所有方法的返回值都是 json 格式,@RequestMapping("/students")註解來指定當前控制器的請求路徑;第二點在每個方法上添加@RequestMapping,用來指定當前方法的路由。如上的@GetMapping、@PostMapping、@PutMapping 註解都是@RequestMapping 註解加上對應 method 的組合,只是使用起來更簡潔罷了。

第三步:定義實體類

<code>@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

private Integer id;

private String name;

private Integer age;
}/<code>

第四步:依次請求如上的路由路徑

http://localhost:8080/students/ GET 請求

<code>[
{
"id": 100001,
"name": "jack",
"age": 22
},
{
"id": 100002,
"name": "lucky",
"age": 23
},
{
"id": 100003,
"name": "jone",
"age": 24
},
{
"id": 100004,
"name": "lucy",
"age": 25
},
{
"id": 100005,
"name": "lily",
"age": 26
}
]/<code>

http://localhost:8080/students/id/2 GET 請求

<code>{
"id": 999999,
"name": "default",
"age": 18
}/<code>

http://localhost:8080/students/ POST 請求

請求參數:

<code>{
\t"id":100006,
\t"name":"add-student",
\t"age":222
}/<code>

響應結果:

<code>[
{
"id": 100001,
"name": "jack",
"age": 22
},
{
"id": 100002,
"name": "lucky",
"age": 23
},
{
"id": 100003,
"name": "jone",
"age": 24
},
{
"id": 100004,
"name": "lucy",
"age": 25
},
{
"id": 100005,
"name": "lily",
"age": 26
},
{
"id": 100006,
"name": "add-student",
"age": 222

}
]/<code>

http://localhost:8080/students/ PUT 請求

請求參數:

<code>{
\t"id":100006,
\t"name":"add-student2",
\t"age":222
}/<code>

響應結果:

<code>[
{
"id": 100001,
"name": "jack",
"age": 22
},
{
"id": 100002,
"name": "lucky",
"age": 23
},
{
"id": 100003,
"name": "jone",
"age": 24
},
{
"id": 100004,
"name": "lucy",
"age": 25
},
{
"id": 100005,
"name": "lily",
"age": 26
},
{
"id": 100006,
"name": "add-student2",
"age": 222
}
]/<code>

到這裡一個基於 Rest 風格的 Web 應用已經搭建完成。在實際的開發過程中,我們可以希望我們的 json 數據中的字段是下劃線風格的,那麼我們需要怎麼做?

將如上實體類和控制器拷貝一下,然後將其修改為 Person、PersonController,具體代碼如下

<code>@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Person {

private Integer personId;

private String personName;

private Integer personAge;
}/<code>
<code>@RestController
@RequestMapping("/persons")
public class PersonController {

private static List<person> personList = new ArrayList<>();

static {
personList.add(new Person(100001, "jack", 22));
personList.add(new Person(100002, "lucky", 23));
personList.add(new Person(100003, "jone", 24));
personList.add(new Person(100004, "lucy", 25));
personList.add(new Person(100005, "lily", 26));
}

@GetMapping("/")
public List<person> listPerson() {
return personList;
}

@GetMapping("id/{id}")
public Person getPerson(@PathVariable("id") Integer id) {
return personList.stream()
.filter(person -> Objects.equals(person.getPersonId(), id))
.findFirst()
.orElse(new Person(999999, "default", 18));
}

@PostMapping("/")
public List<person> addPerson(@RequestBody Person person) {
personList.add(person);
return personList;

}

@PutMapping("/")
public List<person> updatePerson(@RequestBody Person person) {
personList.removeIf(p -> Objects.equals(p.getPersonId(), person.getPersonId()));
personList.add(person);
return personList;
}
}/<person>/<person>/<person>/<person>/<code>

http://localhost:8080/persons/ GET 請求

<code>[
{
"person_id": 100001,
"person_name": "jack",
"person_age": 22
},
{
"person_id": 100002,
"person_name": "lucky",
"person_age": 23
},
{
"person_id": 100003,
"person_name": "jone",
"person_age": 24
},
{
"person_id": 100004,
"person_name": "lucy",
"person_age": 25
},
{
"person_id": 100005,
"person_name": "lily",
"person_age": 26
}
]/<code>

http://localhost:8080/persons/ POST 請求

請求參數:

<code>{
\t"person_id":100006,
\t"person_name":"add-student",
\t"person_age":222
}/<code>

響應結果:

<code>[
{
"person_id": 100001,
"person_name": "jack",
"person_age": 22
},
{
"person_id": 100002,
"person_name": "lucky",
"person_age": 23
},
{
"person_id": 100003,
"person_name": "jone",
"person_age": 24
},
{
"person_id": 100004,
"person_name": "lucy",
"person_age": 25
},
{
"person_id": 100005,
"person_name": "lily",
"person_age": 26
},
{
"person_id": 100006,
"person_name": "add-student",
"person_age": 222
}
]/<code>

如上實現了我們提出的第二個疑問,乍一看和之前的代碼除了名字之外沒有什麼區別,仔細觀察會發現 Person 實體類上多了一個@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)註解,該註解的意思就是當前實體字段採用下滑線的風格。

@JsonNaming 註解的其它命名策略

編號策略示例1SnakeCaseStrategyperson_id2KebabCaseStrategyperson-id3UpperCamelCaseStrategyPersonId4LowerCaseStrategypersonid

專車總結

創建一個 Web 應用步驟:

第一步:創建一個啟動類,需要使用@SpringBootApplication 註解標註,並調用 SpringApplication.run 方法

第二步:創建控制器,使用@RestController 和@RequestMapping 標註

第三步:如果希望得到不同格式的 json 數據,可以使用@JsonNaming 註解指定命名策略

今天的教程就講到這裡,更多敬請關注後續更新。


分享到:


相關文章: