簡體   English   中英

Spring MVC - 如何在 ResponseEntity 方法中返回視圖?

[英]Spring MVC - How do I return a view in a ResponseEntity method?

我有問題。 我不知道如何在返回類型為ResponseEntity的方法中返回視圖。 我想用我的控制器下載一個文件。 如果上傳了文件,下載工作正常。 如果沒有上傳文件,它應該什么都不做(返回實際視圖)。

現在我不知道該怎么做,因為我猜它不可能返回視圖(為此我需要返回類型字符串)。

你有什么想法嗎?

@Controller
public class FileDownloadController {

  @RequestMapping(value="/download", method = RequestMethod.GET)
  public ResponseEntity fileDownload (@Valid DownloadForm form, BindingResult result) throws IOException{

      RestTemplate template = new RestTemplate();
      template.getMessageConverters().add(new FormHttpMessageConverter());

      HttpEntity<String> entity = new HttpEntity<String>(createHttpHeaders("test.jpg", "image/jpeg"));

      UrlResource url = new UrlResource("www.thisismyurl.com/images" + form.getImageId());

      return new ResponseEntity<>(new InputStreamResource(url.getInputStream()), createHttpHeaders("test.jpg", "image/jpeg"), HttpStatus.OK);

  }

  private HttpHeaders createHttpHeaders(String filename, String contentType) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAll(getHttpHeaderMap(filename, contentType));
    return headers;
  }

  private Map<String,String> getHttpHeaderMap(String filename, String contentType) {
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-disposition", "attachment; filename=\"" + filename + "\"");
    headers.put("Content-Type", contentType);
    return headers;
  }
}

嗨,我曾經在我的項目中遇到過類似的問題,即,我必須根據某些邏輯對不同的返回類型視圖與字符串進行處理。

首先,當您將響應實體作為返回類型時,絕對不可能返回模型和視圖。

我使用通用返回類型解決了這個問題

public <T> T fileDownload (@Valid DownloadForm form, BindingResult result) throws IOException{

    //your code
   //here you can return response entity or 
   //modelAndView based on your logic

  }

我發現這適用於 Spring Boot 2 和 JSP 視圖:

@GetMapping(value = "/view/theobject/{id}")
public Object getDomainObject(ModelAndView mav, @PathVariable Long id) {
    Optional<DomainObject> theObject = svc.getDomainObject(id);
    if (theObject.isPresent()) {
        mav.setViewName("viewdomainobject");
        mav.addObject("theObject", theObject.get());
        return mav;
    }
    return ResponseEntity.notFound().build();
}

不需要令人不快的<T> T泛型返回類型,也不需要轉換返回的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM