繁体   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