简体   繁体   中英

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

I have a problem. I don't know how to return a view in a method with a return type of ResponseEntity . I want to download a file with my controller. The download works fine if a file was uploaded. If no file were uploaded, it just should do nothing (return the actual view).

Now I´m not sure how to do this because I guess it's not possible returning a view (For that I needed return-type String).

Do you have any idea?

@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;
  }
}

Hi i had a similar problem in my project once, ie, I have to different return types view vs string based on some logic.

First it's definitely not possible to return a model and view when you have response entity as return type.

I solved this using generic return type

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

  }

I've found that this works with Spring Boot 2 and JSP views:

@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();
}

There's no need for the unpleasant <T> T generic return type, or casting the returned object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM