SpringBoot中各種Controller的寫(xiě)法
SpringBoot各種Controller寫(xiě)法
最近玩SpingBoot,以下是一些Controller的各種寫(xiě)法
本文我們將分為四部分:
- 1、Controller的類(lèi)型(傳統(tǒng)的 和 REST)
- 2、路由(Routes)
- 3、如何接收數(shù)據(jù)
- 4、Controller示例
Controller 類(lèi)型
你也許每天都在使用Spring ,但你知道controller有幾種類(lèi)型嗎?其實(shí)controller是有兩種的,一種就是傳統(tǒng)的web的那種controller,而另外一種就是REST類(lèi)型的controller。
@Controller 通常是被使用服務(wù)于web 頁(yè)面的。默認(rèn),你的controller方法返回的是一個(gè)string 串,是表示要展示哪個(gè)模板頁(yè)面或者是要跳轉(zhuǎn)到哪里去。
@RestController 就是專(zhuān)門(mén)用在編寫(xiě)API的時(shí)候,特別那種返回一個(gè)JSON,或者是XML等等。然后方法返回的是可以是一個(gè)對(duì)象,是一個(gè)可以被序列化的對(duì)象。
當(dāng)然了你也可以通過(guò)controller來(lái)實(shí)現(xiàn)返回JSON、XML這些。只是這里為了"REST",得另立門(mén)戶(hù),這樣會(huì)更加的清晰明了。
路由(Routes)
這里的路由就是指http method。(GET,POST,PUT,PATCH,DELETE)。
HTTP Methods
在Spring boot中,http method可以被用類(lèi)似“*Mapping”的格式來(lái)表示:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
然后這些注解中可以添加path,像下面這樣:
例子:
@GetMapping("/users")
一個(gè)比較典型的REST controller 一般是像下面這樣來(lái)映射路由的:
@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(...) {...} }
還有一種比較常見(jiàn)的做法是通過(guò)在controller類(lèi)上添加一個(gè)@RequestMapping注解。這樣相當(dāng)于可以把上面的所有的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的方法可以去指定一個(gè)返回狀態(tài)碼。默認(rèn)的是返回一個(gè)200 OK,如果是沒(méi)有返回值(void)則返回 204 No Content。
@PostMapping @ResponseStatus(HttpStatus.CREATED) public User create(...) {...}
路徑變量
你可以通過(guò)添加@PathVariable注解來(lái)把路徑上的值捕獲下來(lái):
// DELETE /users/123 @DeleteMapping("/users/{id}") public void delete(@PathVariable long id) {...}
默認(rèn)情況下,參數(shù)名必須要和路徑上的變量名一樣。
但你也可以通過(guò)下面的方式來(lái)修改,就是你通過(guò)給@PathVariable賦值為路徑變量名,然后參數(shù)名就可以是不一樣的了:
// GET /users/me@example.com/edit @GetMapping("/users/{email}/edit" public String edit(@PathVariable("email") String userEmail) {...}
接收數(shù)據(jù)
查詢(xún)字符參數(shù)
如果是通過(guò)?xxx=xxx&yyy=yyy來(lái)傳遞過(guò)來(lái)的參數(shù),那么我們可以通過(guò)@RequestParam來(lái)獲取:
// GET /users?count=10 @GetMapping("/users") public List<User> index(@RequestParam int count) {...}
默認(rèn)的話,變量名必須要和查詢(xún)字符參數(shù)是一樣的。你也可以通過(guò)下面的方式來(lái)修改:
// GET /users?num_per_page=50 @GetMapping("/users") public List<User> index(@RequestParam("num_per_page") int numPerPage) {...}
提交HTML表單數(shù)據(jù)
如果我們想要?jiǎng)?chuàng)建一個(gè)用戶(hù)。這時(shí)候,我么可能在前端,寫(xiě)下面這樣一個(gè)form:
<form action="/users" method="POST"> ? <input name="name"/> ? <input name="email"/> ? <button type="submit">Create User</button> </form>
現(xiàn)在我們創(chuàng)建一個(gè)請(qǐng)求模型,用來(lái)匹配我們的前端form結(jié)構(gòu):
class UserCreateRequest { ? ? ? ?private String name; ? ? ? ?private String email; ? ? ? ?/* Getters & Setters omitted */ }
然后我們就可以在controller對(duì)應(yīng)的方法上來(lái)捕獲form里的值,我們通過(guò)對(duì)參數(shù)添加一個(gè)@ModelAttribute注解就可以實(shí)現(xiàn)了:
@PostMapping("/users") public User create(@ModelAttribute UserCreateRequest request) {...}
提交JSON
就像上面例子那樣,我們創(chuàng)建一個(gè)用戶(hù),然后是一個(gè)JSON格式:
{ "name": "Som Eone", "email": "someone@example.com"}
然后請(qǐng)求模型還是沿用之前的:
class UserCreateRequest { private String name; private String email;? }
然后我們使用@RequestBody來(lái)捕獲前端發(fā)送過(guò)來(lái)的JSON串,然后反序列化到我們的請(qǐng)求模型UserCreateRequest:
@PostMapping public User create(@RequestBody UserCreateRequest request) {...}
Controller 舉例
以下是使用上述所有注解創(chuàng)建Controller的示例。 沒(méi)有具體邏輯,只是簡(jiǎn)單的展示上面說(shuō)到的各個(gè)注解。
傳統(tǒng)的controller
這類(lèi)型的controller返回值表示要展示的頁(yè)面或要跳轉(zhuǎn)到哪個(gè)請(qǐng)求。
@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
這類(lèi)型的controller返回值是一些對(duì)象,這些對(duì)象要被序列化成JSON、XML等其他格式,并不是表示要跳轉(zhuǎn)到哪個(gè)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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Java Socket實(shí)現(xiàn)一個(gè)簡(jiǎn)易在線聊天功能(一)
這篇文章主要給大家介紹基于Java Socket實(shí)現(xiàn)一個(gè)簡(jiǎn)易在線聊天功能(一),分為客戶(hù)端和服務(wù)端兩段代碼,非常具有參考價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-05-05解讀String字符串導(dǎo)致的JVM內(nèi)存泄漏問(wèn)題
這篇文章主要介紹了解讀String字符串導(dǎo)致的JVM內(nèi)存泄漏問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07mybatis-generator自動(dòng)生成dao、mapping、bean配置操作
這篇文章主要介紹了mybatis-generator自動(dòng)生成dao、mapping、bean配置操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08java實(shí)現(xiàn)簡(jiǎn)單驗(yàn)證碼生成
這篇文章主要介紹了java實(shí)現(xiàn)簡(jiǎn)單驗(yàn)證碼生成,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10Druid基本配置及內(nèi)置監(jiān)控使用_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Druid基本配置及內(nèi)置監(jiān)控使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08Java 對(duì)HashMap進(jìn)行排序的三種常見(jiàn)方法
這篇文章主要介紹了Java 對(duì)HashMap進(jìn)行排序的三種常見(jiàn)方法,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-10-10解決表單post,get到springMVC后臺(tái)亂碼的問(wèn)題
下面小編就為大家分享一篇解決表單post,get到springMVC后臺(tái)亂碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01