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.
- How can I redirect the user — let’s pretend they don’t have the permissions to access this page? How can I redirect them to a separate controller?
- Am I able to set the response encoding?
- Can I achieve either of these two without bringing in the HttpResponse as a parameter to my RequestMapping?
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.