SpringBoot中各種Controller的寫法
SpringBoot各種Controller寫法
最近玩SpingBoot,以下是一些Controller的各種寫法
本文我們將分為四部分:
- 1、Controller的類型(傳統(tǒng)的 和 REST)
- 2、路由(Routes)
- 3、如何接收數(shù)據(jù)
- 4、Controller示例
Controller 類型
你也許每天都在使用Spring ,但你知道controller有幾種類型嗎?其實controller是有兩種的,一種就是傳統(tǒng)的web的那種controller,而另外一種就是REST類型的controller。
@Controller 通常是被使用服務于web 頁面的。默認,你的controller方法返回的是一個string 串,是表示要展示哪個模板頁面或者是要跳轉(zhuǎn)到哪里去。
@RestController 就是專門用在編寫API的時候,特別那種返回一個JSON,或者是XML等等。然后方法返回的是可以是一個對象,是一個可以被序列化的對象。
當然了你也可以通過controller來實現(xiàn)返回JSON、XML這些。只是這里為了"REST",得另立門戶,這樣會更加的清晰明了。
路由(Routes)
這里的路由就是指http method。(GET,POST,PUT,PATCH,DELETE)。
HTTP Methods
在Spring boot中,http method可以被用類似“*Mapping”的格式來表示:
@GetMapping@PostMapping@PutMapping@PatchMapping@DeleteMapping
然后這些注解中可以添加path,像下面這樣:
例子:
@GetMapping("/users")一個比較典型的REST controller 一般是像下面這樣來映射路由的:
@RestController
public class UsersController { ??
? ?@GetMapping("/users") ? ?
? ? public List<User> index() {...} ?
? ? @GetMapping("/users/{id}") ? ?
? ? public User show(...) {...}
? ? @PostMapping("/users") ? ?
? ? public User create(...) {...} ?
? ? @PutMapping("/users/{id}") ??
? ? public User update(...) {...} ? ?
? ? @DeleteMapping("/users/{id}") ? ?
? ? public void delete(...) {...}
}還有一種比較常見的做法是通過在controller類上添加一個@RequestMapping注解。這樣相當于可以把上面的所有的mapping前綴添加到這里。
像下面這樣(基于上面的例子修改):
@RestController
@RequestMapping("/users")
public class UsersController {
? ? @GetMapping
? ? public List<User> index() {...}
? ? @GetMapping("{id}") ? ?
? ? public User show(...) {...} ??
? ? @PostMapping
? ? public User create(...) {...}?
? ? @PutMapping("{id}") ??
? ? public User update(...) {...} ??
? ? @DeleteMapping("{id}") ? ?
? ? public void delete(...) {...}
}返回狀態(tài)
Controller的方法可以去指定一個返回狀態(tài)碼。默認的是返回一個200 OK,如果是沒有返回值(void)則返回 204 No Content。
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User create(...) {...}路徑變量
你可以通過添加@PathVariable注解來把路徑上的值捕獲下來:
// DELETE /users/123
@DeleteMapping("/users/{id}")
public void delete(@PathVariable long id) {...}默認情況下,參數(shù)名必須要和路徑上的變量名一樣。
但你也可以通過下面的方式來修改,就是你通過給@PathVariable賦值為路徑變量名,然后參數(shù)名就可以是不一樣的了:
// GET /users/me@example.com/edit
@GetMapping("/users/{email}/edit"
public String edit(@PathVariable("email") String userEmail) {...}接收數(shù)據(jù)
查詢字符參數(shù)
如果是通過?xxx=xxx&yyy=yyy來傳遞過來的參數(shù),那么我們可以通過@RequestParam來獲取:
// GET /users?count=10
@GetMapping("/users")
public List<User> index(@RequestParam int count) {...}默認的話,變量名必須要和查詢字符參數(shù)是一樣的。你也可以通過下面的方式來修改:
// GET /users?num_per_page=50
@GetMapping("/users")
public List<User> index(@RequestParam("num_per_page") int numPerPage) {...}提交HTML表單數(shù)據(jù)
如果我們想要創(chuàng)建一個用戶。這時候,我么可能在前端,寫下面這樣一個form:
<form action="/users" method="POST"> ? <input name="name"/> ? <input name="email"/> ? <button type="submit">Create User</button> </form>
現(xiàn)在我們創(chuàng)建一個請求模型,用來匹配我們的前端form結(jié)構(gòu):
class UserCreateRequest { ? ?
? ?private String name; ? ?
? ?private String email; ? ?
? ?/* Getters & Setters omitted */
}然后我們就可以在controller對應的方法上來捕獲form里的值,我們通過對參數(shù)添加一個@ModelAttribute注解就可以實現(xiàn)了:
@PostMapping("/users")
public User create(@ModelAttribute UserCreateRequest request) {...}提交JSON
就像上面例子那樣,我們創(chuàng)建一個用戶,然后是一個JSON格式:
{ "name": "Som Eone", "email": "someone@example.com"}然后請求模型還是沿用之前的:
class UserCreateRequest {
private String name;
private String email;?
}然后我們使用@RequestBody來捕獲前端發(fā)送過來的JSON串,然后反序列化到我們的請求模型UserCreateRequest:
@PostMapping
public User create(@RequestBody UserCreateRequest request) {...}Controller 舉例
以下是使用上述所有注解創(chuàng)建Controller的示例。 沒有具體邏輯,只是簡單的展示上面說到的各個注解。
傳統(tǒng)的controller
這類型的controller返回值表示要展示的頁面或要跳轉(zhuǎn)到哪個請求。
@Controller
@RequestMapping("/users")
public class UsersController { ? ?
? ?@GetMapping
? ? public String index() { ? ? ? ?
? ? ? ? return "users/index";
? ? } ? ?
? ? @GetMapping("{id}") ? ?
? ? public String show(@PathVariable long id) { ? ? ? ?
? ? ? ? ?return "users/show";
? ? } ? ?
? ? @PostMapping
? ? @ResponseStatus(HttpStatus.CREATED) ? ?
? ? public String create(@ModelAttribute UserCreateRequest request) {
? ? ? return "redirect:/users";
? ? } ? ?
? ? @PutMapping("{id}") ? ?
? ? public String update(@PathVariable long id, @RequestBody UserUpdateRequest request) { ? ? ? ?
? ? ? ?return "redirect:/users/" + id;
? ? } ??
? ? @DeleteMapping("{id}") ? ?
? ? public String delete(@PathVariable long id) { ? ? ? ?
? ? ? ? return "redirect:/users";
? ? }
}REST controller
這類型的controller返回值是一些對象,這些對象要被序列化成JSON、XML等其他格式,并不是表示要跳轉(zhuǎn)到哪個HTML模板。
@RestController
@RequestMapping("/users")
public class UsersController { ? ?
? ?@GetMapping
? ? public List<User> index() { ? ? ? ?return new ArrayList<User>();
? ? } ??
? ? @GetMapping("{id}") ? ?
? ? public User show(@PathVariable long id) { ? ? ? ?return new User();
? ? } ? ?
? ? @PostMapping
? ? @ResponseStatus(HttpStatus.CREATED) ? ?
? ? public User create(@RequestBody UserCreateRequest request) {
? ? ? ?return new User();
? ? } ? ?
? ? @PutMapping("{id}") ? ?
? ? public User update(@PathVariable long id, @RequestBody UserUpdateRequest request) { ? ? ? ?
? ? ? ?return new User();
? ? } ? ?
? ? @DeleteMapping("{id}") ? ?
? ? public void delete(@PathVariable long id) {}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Maven pom的distributionManagement配置方式
文章主要介紹了Maven的distributionManagement配置方式,以及它的作用、配置方法和重要性,distributionManagement用于指定構(gòu)件的發(fā)布位置,包括下載URL、狀態(tài)等,文章還詳細解釋了如何配置repository和snapshotRepository,以及它們的用途和區(qū)別2025-01-01
springboot之端口設置和contextpath的配置方式
這篇文章主要介紹了springboot之端口設置和contextpath的配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
解決feign之間文件上傳報錯:Error converting request body
這篇文章主要介紹了解決feign之間文件上傳報錯:Error converting request body的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-05-05
Java如何實現(xiàn)數(shù)據(jù)壓縮所有方式性能測試
本文介紹了多種壓縮算法及其在Java中的實現(xiàn),包括LZ4、BZip2、Deflate、Gzip和7z等,LZ4以其高效的壓縮和解壓縮速度而受到青睞,特別是在大數(shù)據(jù)處理場景中,通過對比不同壓縮算法的性能和壓縮率,我們選擇了最適合當前項目需求的壓縮工具2025-02-02
JavaMail實現(xiàn)發(fā)送超文本(html)格式郵件的方法
這篇文章主要介紹了JavaMail實現(xiàn)發(fā)送超文本(html)格式郵件的方法,實例分析了java發(fā)送超文本文件的相關技巧,需要的朋友可以參考下2015-05-05
Java 實現(xiàn)實時監(jiān)聽文件夾是否有新文件增加并上傳服務器功能
本文中主要陳述一種實時監(jiān)聽文件夾中是否有文件增加的功能,可用于實際文件上傳功能的開發(fā)。本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下吧2019-09-09

