在程式設計師的日常工作中,Web開發應該是佔比很重的一部分,至少我工作以來,開發的系統基本都是Web端訪問的系統,Web開發在這幾年也是經歷了很快的發展,前端也顯得越來越重要,現在很多大一點的公司都實行前後端分離,讓後端和前端只專注於自己的事,所謂術業有專攻,我個人也非常建議前後端分離。
既然前後端分離了,那麼後端肯定需要提供Web Api介面給到前端,並返回前端需要的資料。
在Spring Boot中,開發Web Api介面主要使用以下幾個註解:
- @Controller
- @ResponseBody
- @RestController
- @RequestMapping
- @PathVariable
其實,這些註解在Spring MVC裡都有了,所以Spring Boot裡的用法也和Spring MVC裡基本一樣。
在Spring Boot之所以能使用,是因為在spring-boot-starter-web 這個starter pom中,已經引用了spring-web和spring-webmvc。
接下來,我們通過具體例子來講解下各個註解的使用方法。
1.@Controller
新建控制器HelloController,新增@Controller註解,新增1個方法sayHello,新增@RequestMapping註解,程式碼如下:
package com.zwwhnly.springbootdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
}
複製程式碼
執行專案,在瀏覽器輸入http://localhost:8080/hello訪問,發現報如下錯誤:
報錯的原因是未找到對應的模板,那麼如何解決呢?
我們先講解下第一種解決方法,新增下thymeleaf模板,首先修改pom檔案,新增如下配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
複製程式碼
如果沒有設定自動匯入maven包的話,IDEA右下角會提示你匯入,點選“Import Changes”。
然後在resources/templates目錄下,新建hello.html檔案(內容先隨便寫),再次執行專案,訪問http://localhost:8080/hello,發現訪問正常:
2.@ResponseBody
還有一種更簡單的方法是在控制器上新增@ResponseBody註解:
package com.zwwhnly.springbootdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
}
複製程式碼
此時的執行結果(直接返回字串):
hello
3.@RestController
@RestController是Spring4.0推出的組合註解,相當於@Controller+@ResponseBody,我們看下它的原始碼,也能看出:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(
annotation = Controller.class
)
String value() default "";
}
複製程式碼
此時我們就可以將程式碼簡化為:
@RestController
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
}
複製程式碼
4.@RequestMapping
@RequestMapping註解主要用來配置url對映,既可以新增到控制器上,也可以新增到控制器下的方法上,新增到方法上是對新增到控制器上的補充,舉例說明:
新建圖書類Book:
package com.zwwhnly.springbootdemo.model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Book {
private Integer bookId;
private String bookName;
private String bookAuthor;
private Date purchaseDate;
public Book(Integer bookId, String bookName, String bookAuthor, String purchaseDate) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
this.bookId = bookId;
this.bookName = bookName;
this.bookAuthor = bookAuthor;
this.purchaseDate = simpleDateFormat.parse(purchaseDate);
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
public Date getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
}
}
複製程式碼
在HelloController中新增方法getBookList:
@RequestMapping(value = "/getBookList", method = RequestMethod.GET)
public List<Book> getBookList() {
List<Book> books = new ArrayList<>();
try {
Book book1 = new Book(1, "平凡的世界", "路遙", "2010-01-01");
Book book2 = new Book(2, "人生", "路遙", "2011-01-01");
books.add(book1);
books.add(book2);
} catch (ParseException e) {
e.printStackTrace();
}
return books;
}
複製程式碼
執行專案在瀏覽器輸入http://localhost:8080/getBookList,結果為:
// 20190424140621
// http://localhost:8080/getBookList
[
{
"bookId": 1,
"bookName": "平凡的世界",
"bookAuthor": "路遙",
"purchaseDate": "2009-12-31 16:00:00"
},
{
"bookId": 2,
"bookName": "人生",
"bookAuthor": "路遙",
"purchaseDate": "2010-12-31 16:00:00"
}
]
複製程式碼
然後我們在HelloController上也加上@RequestMapping註解:
package com.zwwhnly.springbootdemo.controller;
import com.zwwhnly.springbootdemo.model.Book;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(value = "hello")
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
@RequestMapping(value = "/getBookList", method = RequestMethod.GET)
public List<Book> getBookList() {
List<Book> books = new ArrayList<>();
try {
Book book1 = new Book(1, "平凡的世界", "路遙", "2010-01-01");
Book book2 = new Book(2, "人生", "路遙", "2011-01-01");
books.add(book1);
books.add(book2);
} catch (ParseException e) {
e.printStackTrace();
}
return books;
}
}
複製程式碼
此時兩個方法的訪問地址就分別變為了:http://localhost:8080/hello/hello,http://localhost:8080/hello/getBookList。
5.@PathVariable
@PathVariable註解用來獲取url中的資料,以下為具體的使用方法,
在HelloController控制器中新增方法getBook,通過佔位符傳遞bookId:
@RequestMapping(value = "/getBook/{bookId}", method = RequestMethod.GET)
public Book getBook(@PathVariable Integer bookId) {
Book book = null;
List<Book> books = new ArrayList<>();
try {
Book book1 = new Book(1, "平凡的世界", "路遙", "2010-01-01");
Book book2 = new Book(2, "人生", "路遙", "2011-01-01");
books.add(book1);
books.add(book2);
book = books.get(bookId - 1);
} catch (ParseException e) {
e.printStackTrace();
}
return book;
}
複製程式碼
執行專案,在瀏覽器中訪問http://localhost:8080/hello/getBook/1,結果如下:
// 20190424145348
// http://localhost:8080/hello/getBook/1
{
"bookId": 1,
"bookName": "平凡的世界",
"bookAuthor": "路遙",
"purchaseDate": "2009-12-31 16:00:00"
}
複製程式碼
注意:佔位符裡的名稱必須和引數名完全一致,區分大小寫,否則訪問會報500錯誤。
如果想不一致,可以寫成如下方式:
@RequestMapping(value = "/getBook/{bookId}", method = RequestMethod.GET)
public Book getBook(@PathVariable("bookId") Integer bookIndex) {
......
}
複製程式碼
這種方式也要求,PathVariable的value屬性值必須與佔位符裡的名稱完全一致。
好了,本篇文章就先講解這麼多,其它註解後續再單獨釋出文章講解。
6.原始碼地址
原文地址:Spring Boot入門(四):開發Web Api介面常用註解總結
部落格地址:www.zwwhnly.com
原始碼地址:github.com/zwwhnly/spr…
歡迎大家下載,有問題可以多多交流。
7.參考連結
用Spring Boot開發一個web API 介面返回資料
SpringBoot 中常用註解@Controller/@RestController/@RequestMapping介紹