通常情況下,在前后端分離的大背景下,我們后臺(tái)服務(wù)返回給前端的通常都是格式化的數(shù)據(jù),比如Json,開始的時(shí)候,我們用json包生產(chǎn)一個(gè)json的字符串,配合http 協(xié)議的一些API 來自定義實(shí)現(xiàn)
十年的集美網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。全網(wǎng)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整集美建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。成都創(chuàng)新互聯(lián)公司從事“集美網(wǎng)站設(shè)計(jì)”,“集美網(wǎng)站推廣”以來,每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
spring發(fā)展到現(xiàn)在,已經(jīng)都包裝出來了通用的處理類:ResponseEntity ,此類繼承自HttpEntity
public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;
/**
* Create a new {@code ResponseEntity} with the given status code, and no body nor headers.
* @param status the status code
*/
public ResponseEntity(HttpStatus status) {
this(null, null, status);
}
/**
* Create a new {@code ResponseEntity} with the given body and status code, and no headers.
* @param body the entity body
* @param status the status code
*/
public ResponseEntity(@Nullable T body, HttpStatus status) {
this(body, null, status);
}
并且做了擴(kuò)展,用來處理http請(qǐng)求過程中的狀態(tài)碼 ,header,body 等數(shù)據(jù)。
ResponseEntity是一種泛型類型。因此,我們可以使用任何類型作為響應(yīng)主體:
@Controller
public class XXXController{@GetMapping("/hello")
br/>@GetMapping("/hello")
return new ResponseEntity<>("Hello !", HttpStatus.OK);
}這里字符串"Hello World!"作為字符串返回給REST端。
我們可以設(shè)置HTTP標(biāo)頭:
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}
設(shè)置自定義標(biāo)頭:
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set")如果將一個(gè)對(duì)象放入:
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>(new User(‘jdon’), HttpStatus.OK);
}返回是JSON字符串:
[ { ‘name’: 'jdon'}]
下面是返回對(duì)象的JSON列表:
public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() {
return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND);
}以上是通過ResponseEntity這個(gè)對(duì)象在代碼中靈活操控響應(yīng),但是在一般情況下我們只是想返回一個(gè)帶有數(shù)據(jù)的正常響應(yīng),那么只要使用@注解即可
@ResponseBody
在類級(jí)別使用@Controller標(biāo)注情況下, @ResponseBody注解告訴返回的對(duì)象將自動(dòng)序列化為JSON,并通過回控制器的HttpResponse對(duì)象。
@Controller
public class XXXController{
@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}
將返回客戶端JSON字符串:
[ { ‘name’: Thanks For Posting!!!"}]
在@RestController注解了類的情況下,我們就不需要再使用@ResponseBody了,可以直接返回對(duì)象,并使用ResponseStatus返回狀態(tài)碼!
@ResponseStatus
ResponseStatus雖然只是規(guī)定了返回的狀態(tài),但是只需要標(biāo)注在方法上,簡單,而且狀態(tài)碼與返回類型分離,比較清晰。我們將上面返回對(duì)象列表的代碼使用ResponseStatus改寫如下,注意類級(jí)別@RestController:
@RestController
public class XXXController{
@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}
這也會(huì)返回客戶端JSON字符串:
[ { ‘name’: Thanks For Posting!!!"}]
這樣的代碼更加專注于業(yè)務(wù)。
直接操控響應(yīng)
Spring還允許我們直接訪問javax.servlet.http.HttpServletResponse對(duì)象; 我們只需要將它聲明為方法參數(shù):
@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter().println("Hello World!");
}由于Spring在底層實(shí)現(xiàn)之上提供了抽象和附加功能,因此如果以這種方式直接操縱響應(yīng),會(huì)失去很多Spring提供方便功能。
實(shí)例代碼:
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.*;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-03-09T21:32:18.308+08:00")
@Api(value = "tag", tags={ "tag", }, description = "the tag API")
public interface TagApi {
@ApiOperation(value = "獲取問題概要標(biāo)簽列表", notes = "get_issue_summary_tags", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = OperateResult.class),
@ApiResponse(code = 500, message = "system error", response = Void.class) })
@RequestMapping(value = "/tag/{issue_summary_key}/tags",
produces = { "application/json" },
method = RequestMethod.GET)
default ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "項(xiàng)目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
// do some magic!
return new ResponseEntity<OperateResult>(HttpStatus.OK);
}
@ApiOperation(value = "獲取問題概要標(biāo)簽值列表", notes = "get_tag_values", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = OperateResult.class),
@ApiResponse(code = 500, message = "system error", response = Void.class) })
@RequestMapping(value = "/tag/{issue_summary_key}/tag_value/{tag_type}",
produces = { "application/json" },
method = RequestMethod.GET)
default ResponseEntity<OperateResult> getTagValues(@NotNull @ApiParam(value = "項(xiàng)目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey, @ApiParam(value = "標(biāo)簽類型 app: 應(yīng)用 device: 設(shè)備 server_name:服務(wù)名稱 level:級(jí)別 logger:日志 os: 系統(tǒng) user: 用戶 url:URL transaction:事物", required = true) @PathVariable("tag_type") String tagType, @NotNull @Min(1) @ApiParam(value = "當(dāng)前頁數(shù)", required = true, defaultValue = "1") @RequestParam(value = "page_number", required = true, defaultValue = "1") Integer pageNumber, @NotNull @Min(1) @ApiParam(value = "每頁顯示條數(shù)", required = true, defaultValue = "10") @RequestParam(value = "page_size", required = true, defaultValue = "10") Integer pageSize) {
// do some magic!
return new ResponseEntity<OperateResult>(HttpStatus.OK);
}
}
@Controller
public class TagApiController implements TagApi {
private final static Logger logger = LoggerFactory.getLogger(TagApiController.class);
@Autowired
private TagService tagService;
@Override
public ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "項(xiàng)目key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
OperateResult operateResult = new OperateResult();
try {
Preconditions.checkArgument(StringUtils.isNotBlank(projectKey));
Preconditions.checkArgument(StringUtils.isNotBlank(issueSummaryKey));
List<TagDetail> tagValueArrayList = tagService.getIssueSummaryTagList(projectKey, issueSummaryKey);
operateResult = OperateResult.success(tagValueArrayList);
return new ResponseEntity<OperateResult>(operateResult,HttpStatus.OK);
} catch (Exception e) {
logger.error("api getIssueSummaryTags error.{}", e);
operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR,e);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
分享題目:使用springResponseEntity來處理HTTP的返回請(qǐng)求
標(biāo)題鏈接:http://www.chinadenli.net/article0/ighioo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、網(wǎng)站維護(hù)、網(wǎng)站營銷、小程序開發(fā)、App開發(fā)、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)