ResponseEntity

ResponseEntity可以標識整個http相應,包括狀態碼、頭部信息以及響應體內容:

  1. 可以使用任意類型作爲響應體;
  2. 可以通過編程方式指明響應狀態,根據不同場景返回不同狀態;
  3. 設置http響應頭;

ResponseEntity提供了兩個內嵌的構建器接口: HeadersBuilder 和其子接口 BodyBuilder。因此我們能通過ResponseEntity的靜態方法直接訪問。也可以自定義頭信息。

public ResponseEntity DownloadSubjectAttachment(String id) throws IOException {
    Subject subject = subjectMapper.selectSubjectById(id);
    String path = subject.getAttachment();// http://img.eilnhoc.com/group1/M00/02/FD/rBISPFwPJOCAecHCAAPuAGblOL8492.xls
    UrlResource resource = new UrlResource(path);// 對URL進行封裝,下載其對應的資源
    String fileName = subject.getAttachmentName();// GaiEr·GaDuo.jpg
    return ResponseEntity
            .ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(resource.contentLength())
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"))
            .body(resource);
}
@Controller
public class XXXController{

 @GetMapping("/hello")
 public ResponseEntity<String> hello() {
   return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}

@Controller
public class XXXController{

 @GetMapping("/hello")
 public ResponseEntity<String> hello() {
   return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章