Spring MVC-如何在ResponseEntity方法中返回视图?

Bla*_*esR 5 java spring spring-mvc

我有个问题。我不知道如何在返回类型为的方法中返回视图ResponseEntity。我想使用控制器下载文件。如果上传了文件,则下载工作正常。如果没有文件上传,它什么也不做(返回实际视图)。

现在,我不确定如何执行此操作,因为我想不可能返回视图(为此,我需要返回类型为String的字符串)。

你有什么主意吗?

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

嗨,我曾经在我的项目中遇到过类似的问题,即基于某种逻辑,我不得不使用不同的返回类型视图还是字符串。

首先,当您将响应实体作为返回类型时,绝对不可能返回模型并查看。

我使用通用返回类型解决了这个问题

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

  }
Run Code Online (Sandbox Code Playgroud)