Sco*_*ott 13 java spring spring-mvc
我有一个用例,我需要将PDF返回给为我们生成的用户.看来我需要做的就是在这种情况下使用ResponseEntity,但我有一些不太清楚的事情.
我正在使用Spring 3.0.5.示例代码如下:
@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);
}
Run Code Online (Sandbox Code Playgroud)
我真的很想不接受响应......到目前为止,我的控制器都没有这样做,我不想把它全部带进来.
Fel*_*lby 22
注意,这适用于Spring 3.1,不确定原始问题中提到的spring 3.0.5.
在返回ResponseEntity语句中,您要处理重定向,只需在ResponseEntity中添加"Location"标头,将body设置为null并将HttpStatus设置为FOUND(302).
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "http://stackoverflow.com");
return new ResponseEntity<byte []>(null,headers,HttpStatus.FOUND);
Run Code Online (Sandbox Code Playgroud)
这将使您不必更改控制器方法的返回类型.
无论如何,我们决定只显示他们会收到的错误消息,而不是处理重定向(这些是我们在新窗口/选项卡中打开的实例)。
这可能不适用于所有人,但是通过我们添加错误/状态消息的方式,我们无法在发生异常时让这些消息保留在视图上。