Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

java - Spring 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.

  1. 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?
  2. Am I able to set the response encoding?
  3. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...