Spring ResponseEntity

我有一个用例,我需要将PDF返回给为我们生成的用户。 似乎我需要做的是在这种情况下使用ResponseEntity,但我有一些不太清楚的事情。

  1. 如何重定向用户 – 让我们假装他们没有访问此页面的权限? 如何将它们重定向到单独的控制器?
  2. 我可以设置响应编码吗?
  3. 我可以在不将HttpResponse作为参数传入RequestMapping的情况下实现这两个中的任何一个吗?

我正在使用Spring 3.0.5。 示例代码如下:

@Controller @RequestMapping("/generate/data/pdf.xhtml") public class PdfController { @RequestMapping public ResponseEntity 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(PdfGenerator.generateFromKey(itemKey), responseHeaders, HttpStatus.CREATED); } 

我真的很想不参与响应……到目前为止,我的控制器都没有这样做,我不想把它全部带进来。

注意,这适用于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(null,headers,HttpStatus.FOUND); 

这将使您不必更改控制器方法的返回类型。

关于重定向,您需要做的就是将返回类型更改为Object:

 @Controller @RequestMapping("/generate/data/pdf.xhtml") public class PdfController { @RequestMapping public Object generatePdf(@RequestAttribute("key") Key itemKey) { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.valueOf("application/pdf")); if (itemKey == null || !allowedToViewPdf(itemKey)) { return "redirect:/some/path/to/redirect" } //How can I set the response content type to UTF_8 -- I need this //for a separate controller return new ResponseEntity(PdfGenerator.generateFromKey(itemKey), responseHeaders, HttpStatus.CREATED); } 

重定向很容易 – 对于你的处理程序方法的返回String,只是在redirect:前面加上redirect: ,就像return "redirect:somewhere else"

不确定为什么你反对Response对象。 有原因吗? 否则,如果您只是将PDF作为OutputStream流传输到HttpServletResponse对象上,那么您实际上不需要从处理程序方法返回PDF – 您只需要在响应上设置PDF流,您可以将其添加到您的处理程序方法的签名。 有关示例,请参阅http://www.exampledepot.com/egs/javax.servlet/GetImage.html 。

我们决定只显示他们会收到的错误消息,而不是处理重定向(这些是我们在新窗口/标签中打开的实例)。

这可能不适用于所有人,但是通过我们添加错误/状态消息的方式,我们无法在发生exception时将这些消息保留在视图上。