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.
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.
Note, this works in Spring 3.1, not sure about spring 3.0.5 as asked in the original question.
In your return ResponseEntity statement where you want to handle the redirect, just add in a "Location" header to the ResponseEntity, set the body to null and set the HttpStatus to FOUND (302).
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "http://stackoverflow.com");
return new ResponseEntity<byte []>(null,headers,HttpStatus.FOUND);
This will keep you from having to change the return type of the controller method.
Regarding the redirect, all you need to do is change the return type to 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<byte []>(PdfGenerator.generateFromKey(itemKey),
responseHeaders,
HttpStatus.CREATED);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With