Spring ResponseEntity [英] Spring ResponseEntity
问题描述
我有一个用例,我需要将PDF返回给为我们生成的用户。看来我需要做的就是在这种情况下使用ResponseEntity,但我有一些不太清楚的事情。
I have a use case where I need to return a PDF to a user which is generated for us. It seems that what I need to do is utilize the ResponseEntity in this case, but I have a couple of things which are not very clear.
- 如何重定向用户 - 让我们假装他们没有访问此页面的权限?如何将它们重定向到单独的控制器?
- 我能设置响应编码吗?
- 我可以实现这两种中的任何一种而不带来在HttpResponse中作为我的RequestMapping的参数?
我正在使用Spring 3.0.5。示例代码如下:
I'm using Spring 3.0.5. Example code below:
@Controller
@RequestMapping("/generate/data/pdf.xhtml")
public class PdfController {
@RequestMapping
public ResponseEntity<byte []> generatePdf(@RequestAttribute("key") Key itemKey) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.valueOf("application/pdf"));
if (itemKey == null || !allowedToViewPdf(itemKey)) {
//How can I redirect here?
}
//How can I set the response content type to UTF_8 -- I need this
//for a separate controller
return new ResponseEntity<byte []>(PdfGenerator.generateFromKey(itemKey),
responseHeaders,
HttpStatus.CREATED);
}
我真的不想参与回复...没有我的控制器到目前为止已经这样做了,我讨厌必须把它带进来。
I'd really like to not pull in the Response... None of my controllers have done so thus far, and I'd hate to have to bring it in at all.
推荐答案
而不是处理重定向(这些是我们在新的窗口/标签中打开的实例)无论如何我们决定只显示他们会收到的错误消息。
Instead of dealing with redirecting (these are instances which we open in new windows / tabs) anyhow we decided to just display the error message they would have received.
这可能不起作用对于所有人,但是通过我们添加错误/状态消息的方式,我们无法在发生异常时将这些消息保留在视图上。
This likely won't work for all, but with the way we add error / status messages we were unable to get those messages to persist on the view upon exception occurring.
这篇关于Spring ResponseEntity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!