如何使用spring ResponseEntity處理http響應(yīng)
簡(jiǎn)介
使用spring時(shí),達(dá)到同一目的通常有很多方法,對(duì)處理http響應(yīng)也是一樣。本文我們學(xué)習(xí)如何通過(guò)ResponseEntity設(shè)置http相應(yīng)內(nèi)容、狀態(tài)以及頭信息。
ResponseEntity
ResponseEntity標(biāo)識(shí)整個(gè)http相應(yīng):狀態(tài)碼、頭部信息以及相應(yīng)體內(nèi)容。因此我們可以使用其對(duì)http響應(yīng)實(shí)現(xiàn)完整配置。
如果需要使用ResponseEntity,必須在請(qǐng)求點(diǎn)返回,通常在spring rest中實(shí)現(xiàn)。ResponseEntity是通用類型,因此可以使用任意類型作為響應(yīng)體:
@GetMapping("/hello") ResponseEntity<String> hello() { return new ResponseEntity<>("Hello World!", HttpStatus.OK); }
可以通過(guò)編程方式指明響應(yīng)狀態(tài),所以根據(jù)不同場(chǎng)景返回不同狀態(tài):
@GetMapping("/age") ResponseEntity<String> age( @RequestParam("yearOfBirth") int yearOfBirth) { if (isInFuture(yearOfBirth)) { return new ResponseEntity<>( "Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); } return new ResponseEntity<>( "Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); }
另外,還可以設(shè)置http響應(yīng)頭:
@GetMapping("/customHeader") ResponseEntity<String> customHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "foo"); return new ResponseEntity<>( "Custom header set", headers, HttpStatus.OK); }
而且, ResponseEntity提供了兩個(gè)內(nèi)嵌的構(gòu)建器接口: HeadersBuilder 和其子接口 BodyBuilder。因此我們能通過(guò)ResponseEntity的靜態(tài)方法直接訪問(wèn)。
最簡(jiǎn)單的情況是相應(yīng)包括一個(gè)主體及http 200響應(yīng)碼:
@GetMapping("/hello") ResponseEntity<String> hello() { return ResponseEntity.ok("Hello World!"); }
大多數(shù)常用的http 響應(yīng)碼,可以通過(guò)下面static方法:
BodyBuilder accepted(); BodyBuilder badRequest(); BodyBuilder created(java.net.URI location); HeadersBuilder<?> noContent(); HeadersBuilder<?> notFound(); BodyBuilder ok();
另外,可以能使用BodyBuilder status(HttpStatus status)和BodyBuilder status(int status) 方法設(shè)置http狀態(tài)。使用ResponseEntity BodyBuilder.body(T body)設(shè)置http響應(yīng)體:
@GetMapping("/age") ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) { if (isInFuture(yearOfBirth)) { return ResponseEntity.badRequest() .body("Year of birth cannot be in the future"); } return ResponseEntity.status(HttpStatus.OK) .body("Your age is " + calculateAge(yearOfBirth)); }
也可以自定義頭信息:
@GetMapping("/customHeader") ResponseEntity<String> customHeader() { return ResponseEntity.ok() .header("Custom-Header", "foo") .body("Custom header set"); }
因?yàn)锽odyBuilder.body()返回ResponseEntity 而不是 BodyBuilder,需要最后調(diào)用。注意使用HeaderBuilder 不能設(shè)置任何響應(yīng)體屬性。
盡管ResponseEntity非常強(qiáng)大,但不應(yīng)該過(guò)度使用。在一些簡(jiǎn)單情況下,還有其他方法能滿足我們的需求,使代碼更整潔。
替代方法
@ResponseBody
典型spring mvc應(yīng)用,請(qǐng)求點(diǎn)通常返回html頁(yè)面。有時(shí)我們僅需要實(shí)際數(shù)據(jù),如使用ajax請(qǐng)求。這時(shí)我們能通過(guò)@ResponseBody注解標(biāo)記請(qǐng)求處理方法,審批人能夠處理方法結(jié)果值作為http響應(yīng)體。
@ResponseStatus
當(dāng)請(qǐng)求點(diǎn)成功返回,spring提供http 200(ok)相應(yīng)。如果請(qǐng)求點(diǎn)拋出異常,spring查找異常處理器,由其返回相應(yīng)的http狀態(tài)碼。對(duì)這些方法增加@ResponseStatus注解,spring會(huì)返回自定義http狀態(tài)碼。
直接操作相應(yīng)
Spring 也允許我們直接 javax.servlet.http.HttpServletResponse 對(duì)象;只需要申明其作為方法參數(shù):
@GetMapping("/manual") void manual(HttpServletResponse response) throws IOException { response.setHeader("Custom-Header", "foo"); response.setStatus(200); response.getWriter().println("Hello World!"); }
但需要說(shuō)明,既然spring已經(jīng)提供底層實(shí)現(xiàn)的抽象和附件功能,我們不建議直接操作response。
總結(jié):本文我們介紹了spring提供多種方式處理http響應(yīng),以及各自的優(yōu)缺點(diǎn),希望對(duì)你有幫助。
ResponseEntity的基本簡(jiǎn)介
1、ResponseEntity繼承了HttpEntity
可以添加HttpStatus狀態(tài)碼的HttpEntity的擴(kuò)展類。被用于RestTemplate和Controller層方法
2、ResponseEntity可以定義返回的HttpStatus(狀態(tài)碼)
和HttpHeaders(消息頭:請(qǐng)求頭和響應(yīng)頭)HttpStatus的狀態(tài)碼有以下幾種
3、ResponseEntity的優(yōu)先級(jí)高于@ResponseBody
在不是ResponseEntity的情況下才去檢查有沒(méi)有@ResponseBody注解。如果響應(yīng)類型是ResponseEntity可以不寫@ResponseBody注解,寫了也沒(méi)有關(guān)系。
簡(jiǎn)單的說(shuō)@ResponseBody可以直接返回Json結(jié)果,@ResponseEntity不僅可以返回json結(jié)果,還可以定義返回的HttpHeaders和HttpStatus
public ResponseEntity<List<Category>> queryCategoriesByPid(@RequestParam(value = "pid",defaultValue = "0") Long pid){ if(pid == null || pid.longValue()<0){ // 響應(yīng)400,相當(dāng)于ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); return ResponseEntity.badRequest().build(); } //ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); // ResponseEntity.notFound().build(); // ResponseEntity.ok(null); List<Category> categoryList = this.categoryService.queryCategoriesByPid(pid); if(CollectionUtils.isEmpty(categoryList)){ // 響應(yīng)404 return ResponseEntity.notFound().build(); } return ResponseEntity.ok(categoryList); }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- 解決springboot responseentity<string>亂碼問(wèn)題
- 使用ResponseEntity作為的返回值的應(yīng)用
- 常用的ResponseEntity.BodyBuilder和自定義ResponseEntity的實(shí)例
- springmvc @ResponseStatus和ResponseEntity的使用
- SpringMVC使用ResponseEntity實(shí)現(xiàn)文件上傳下載
- SpringMVC返回的ResponseEntity出現(xiàn)亂碼及解決
- 使用spring框架ResponseEntity實(shí)現(xiàn)文件下載
- 使用ResponseEntity處理API返回問(wèn)題
相關(guān)文章
MyBatis使用annonation定義類型映射的簡(jiǎn)易用法示例
這篇文章主要介紹了MyBatis使用annonation定義類型映射的簡(jiǎn)易用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09淺談Spring Data Redis讀不到設(shè)進(jìn)去的值
本文主要介紹了Spring Data Redis怎么讀不到我剛才設(shè)進(jìn)去的值,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09自定義application.yml配置項(xiàng)方式
這篇文章主要介紹了自定義application.yml配置項(xiàng)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07詳解Spring MVC/Boot 統(tǒng)一異常處理最佳實(shí)踐
在 Web 開(kāi)發(fā)中, 我們經(jīng)常會(huì)需要處理各種異常,這篇文章主要介紹了詳解Spring MVC/Boot 統(tǒng)一異常處理最佳實(shí)踐,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01ibatis學(xué)習(xí)之搭建Java項(xiàng)目
本文的主要內(nèi)容是簡(jiǎn)單介紹了ibatis和如何通過(guò)iBatis搭建JAVA項(xiàng)目,包含了一個(gè)相關(guān)實(shí)例,需要的朋友可以參考下。2017-09-09java實(shí)現(xiàn)數(shù)據(jù)庫(kù)的數(shù)據(jù)寫入到txt的方法
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)數(shù)據(jù)庫(kù)的數(shù)據(jù)寫入到txt的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07