使用springResponseEntity來處理HTTP的返回請求

通常情況下,在前后端分離的大背景下,我們后臺服務返回給前端的通常都是格式化的數(shù)據(jù),比如Json,開始的時候,我們用json包生產(chǎn)一個json的字符串,配合http 協(xié)議的一些API 來自定義實現(xiàn)

十年的集美網(wǎng)站建設經(jīng)驗,針對設計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。全網(wǎng)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設備顯示端的尺寸不同,自動調(diào)整集美建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)公司從事“集美網(wǎng)站設計”,“集美網(wǎng)站推廣”以來,每個客戶項目都認真落實執(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);
}
            并且做了擴展,用來處理http請求過程中的狀態(tài)碼 ,header,body 等數(shù)據(jù)。

ResponseEntity是一種泛型類型。因此,我們可以使用任何類型作為響應主體:

@Controller
public class XXXController{@GetMapping("/hello")
br/>@GetMapping("/hello")
return new ResponseEntity<>("Hello !", HttpStatus.OK);
}

這里字符串"Hello World!"作為字符串返回給REST端。

我們可以設置HTTP標頭:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");

return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}

設置自定義標頭:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set")

如果將一個對象放入:

@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>(new User(‘jdon’), HttpStatus.OK);
}

返回是JSON字符串:

[ { ‘name’: 'jdon'}]

下面是返回對象的JSON列表:

public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() {
return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND);
}

以上是通過ResponseEntity這個對象在代碼中靈活操控響應,但是在一般情況下我們只是想返回一個帶有數(shù)據(jù)的正常響應,那么只要使用@注解即可

@ResponseBody
在類級別使用@Controller標注情況下, @ResponseBody注解告訴返回的對象將自動序列化為JSON,并通過回控制器的HttpResponse對象。

@Controller
public class XXXController{

@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}

將返回客戶端JSON字符串:

[ { ‘name’: Thanks For Posting!!!"}]

在@RestController注解了類的情況下,我們就不需要再使用@ResponseBody了,可以直接返回對象,并使用ResponseStatus返回狀態(tài)碼!

@ResponseStatus
ResponseStatus雖然只是規(guī)定了返回的狀態(tài),但是只需要標注在方法上,簡單,而且狀態(tài)碼與返回類型分離,比較清晰。我們將上面返回對象列表的代碼使用ResponseStatus改寫如下,注意類級別@RestController:

@RestController
public class XXXController{

@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}

這也會返回客戶端JSON字符串:

[ { ‘name’: Thanks For Posting!!!"}]

這樣的代碼更加專注于業(yè)務。

直接操控響應
Spring還允許我們直接訪問javax.servlet.http.HttpServletResponse對象; 我們只需要將它聲明為方法參數(shù):

@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter().println("Hello World!");
}

由于Spring在底層實現(xiàn)之上提供了抽象和附加功能,因此如果以這種方式直接操縱響應,會失去很多Spring提供方便功能。

實例代碼:

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 = "獲取問題概要標簽列表", 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 = "項目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 = "獲取問題概要標簽值列表", 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 = "項目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 = "標簽類型 app: 應用 device: 設備 server_name:服務名稱 level:級別 logger:日志 os: 系統(tǒng) user: 用戶 url:URL transaction:事物", required = true) @PathVariable("tag_type") String tagType, @NotNull @Min(1) @ApiParam(value = "當前頁數(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 = "項目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的返回請求
標題鏈接:http://muchs.cn/article0/ighioo.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供服務器托管、網(wǎng)站維護、網(wǎng)站營銷、小程序開發(fā)App開發(fā)、ChatGPT

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設計