[英]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
.我不知道如何在返回类型为
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:我发现这适用于 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();
}
There's no need for the unpleasant <T> T
generic return type, or casting the returned object.不需要令人不快的
<T> T
泛型返回类型,也不需要转换返回的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.