복붙노트

[SPRING] Spring ResponseEntity

SPRING

Spring ResponseEntity

필자에게 생성 된 사용자에게 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);
    }

나는 응답을 끌어 들이고 싶지 않습니다 ... 내 컨트롤러 중 누구도 지금까지 그렇게하지 않았으며 전혀 가져 오지 않아도됩니다.

해결법

  1. ==============================

    1.참고로, 이것은 Spring 3.1에서 작동하며, 원래의 질문에서 Spring 3.0.5에 대해 확신 할 수 없습니다.

    참고로, 이것은 Spring 3.1에서 작동하며, 원래의 질문에서 Spring 3.0.5에 대해 확신 할 수 없습니다.

    리디렉션을 처리하려는 ResponseEntity 문에서 ResponseEntity에 "Location"헤더를 추가하고 본문을 null로 설정하고 HttpStatus를 FOUND (302)로 설정합니다.

    HttpHeaders headers = new HttpHeaders();
    headers.add("Location", "http://stackoverflow.com");
    
    return new ResponseEntity<byte []>(null,headers,HttpStatus.FOUND);
    

    이렇게하면 컨트롤러 메소드의 반환 유형을 변경하지 않아도됩니다.

  2. ==============================

    2.리디렉션과 관련하여 반환 유형을 Object로 변경하면됩니다.

    리디렉션과 관련하여 반환 유형을 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);
        }
    
  3. ==============================

    3.리디렉션은 쉽습니다. 핸들러 메서드의 반환 문자열에 대해서는 "redirect : somewhere else"와 같이 redirect :를 앞에 붙입니다.

    리디렉션은 쉽습니다. 핸들러 메서드의 반환 문자열에 대해서는 "redirect : somewhere else"와 같이 redirect :를 앞에 붙입니다.

    Response 객체를 왜 반대하는지 확신 할 수 없습니다. 이유가 있습니까? 그렇지 않으면 PDF를 HttpServletResponse 객체의 OutputStream으로 스트리밍하는 경우 실제로는 핸들러 메서드에서 PDF를 반환 할 필요가 없습니다. PDF 스트림을 응답에 설정하면됩니다. 핸들러 메소드의 서명. 예제는 http://www.exampledepot.com/egs/javax.servlet/GetImage.html을 참조하십시오.

  4. ==============================

    4.대신 리다이렉션 (이것들은 새로운 윈도우 / 탭에서 열리는 인스턴스입니다)을 처리하는 대신 어쨌든 우리는 그들이 받았을 오류 메시지를 표시하기로 결정했습니다.

    대신 리다이렉션 (이것들은 새로운 윈도우 / 탭에서 열리는 인스턴스입니다)을 처리하는 대신 어쨌든 우리는 그들이 받았을 오류 메시지를 표시하기로 결정했습니다.

    이것은 모든 사람에게 적용되는 것은 아니지만 오류 / 상태 메시지를 추가하는 방식으로 예외가 발생하면 해당 메시지를보기에 유지할 수 없습니다.

  5. from https://stackoverflow.com/questions/6781396/spring-responseentity by cc-by-sa and MIT license