복붙노트

[SPRING] Spring MVC에서, @ResponseBody를 사용할 때 어떻게 MIME 타입 헤더를 설정할 수 있습니까?

SPRING

Spring MVC에서, @ResponseBody를 사용할 때 어떻게 MIME 타입 헤더를 설정할 수 있습니까?

JSON 문자열을 반환하는 Spring MVC 컨트롤러가 있고 mimetype을 application / json으로 설정하고 싶습니다. 어떻게해야합니까?

@RequestMapping(method=RequestMethod.GET, value="foo/bar")
@ResponseBody
public String fooBar(){
    return myService.getJson();
}

비즈니스 객체는 이미 JSON 문자열로 사용할 수 있으므로 MappingJacksonJsonView를 사용하는 것은 해결책이 아닙니다. @ResponseBody는 완벽하지만 MIME 형식을 어떻게 설정할 수 있습니까?

해결법

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

    1.JSON 문자열 대신 도메인 객체를 반환하는 서비스를 리팩터링하고 Spring에서 직렬화를 처리하도록 (내가 작성한 MappingJacksonHttpMessageConverter를 통해) 고려해 보겠습니다. Spring 3.1부터는 구현이 매우 깔끔하게 보입니다.

    JSON 문자열 대신 도메인 객체를 반환하는 서비스를 리팩터링하고 Spring에서 직렬화를 처리하도록 (내가 작성한 MappingJacksonHttpMessageConverter를 통해) 고려해 보겠습니다. Spring 3.1부터는 구현이 매우 깔끔하게 보입니다.

    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
        method = RequestMethod.GET
        value = "/foo/bar")
    @ResponseBody
    public Bar fooBar(){
        return myService.getBar();
    }
    

    코멘트:

    첫째, 또는 @EnableWebMvc를 애플리케이션 구성에 추가해야합니다.

    그런 다음 @RequestMapping 주석의 produce 속성을 사용하여 응답의 내용 유형을 지정합니다. 따라서 MediaType.APPLICATION_JSON_VALUE (또는 "application / json")으로 설정해야합니다.

    마지막으로, Java와 JSON 간의 직렬화 및 비 직렬화가 Spring에 의해 자동으로 처리되도록 Jackson을 추가해야합니다 (Jackson 종속성은 Spring에 의해 감지되고 MappingJacksonHttpMessageConverter는 내부적으로 처리됩니다).

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

    2.ResponseBody 대신 ResponseEntity를 사용하십시오. 이렇게하면 응답 헤더에 액세스 할 수 있고 적절한 콘텐츠 형식을 설정할 수 있습니다. 스프링 문서에 따르면 :

    ResponseBody 대신 ResponseEntity를 사용하십시오. 이렇게하면 응답 헤더에 액세스 할 수 있고 적절한 콘텐츠 형식을 설정할 수 있습니다. 스프링 문서에 따르면 :

    코드는 다음과 같습니다.

    @RequestMapping(method=RequestMethod.GET, value="/fooBar")
    public ResponseEntity<String> fooBar2() {
        String json = "jsonResponse";
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
    }
    
  3. ==============================

    3.@ResponseBody로는이 작업을 수행하지 못할 수도 있지만 다음과 같이하면됩니다.

    @ResponseBody로는이 작업을 수행하지 못할 수도 있지만 다음과 같이하면됩니다.

    package xxx;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @Controller
    public class FooBar {
      @RequestMapping(value="foo/bar", method = RequestMethod.GET)
      public void fooBar(HttpServletResponse response) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(myService.getJson().getBytes());
        response.setContentType("application/json");
        response.setContentLength(out.size());
        response.getOutputStream().write(out.toByteArray());
        response.getOutputStream().flush();
      }
    }
    
  4. ==============================

    4.나는 이것이 가능하다고 생각하지 않는다. 오픈 Jira가있는 것처럼 보입니다.

    나는 이것이 가능하다고 생각하지 않는다. 오픈 Jira가있는 것처럼 보입니다.

    SPR-6702 : @ResponseBody에 응답 Content-Type을 명시 적으로 설정했습니다.

  5. ==============================

    5.org.springframework.http.converter.json.MappingJacksonHttpMessageConverter를 메시지 변환기로 등록하고 메소드에서 객체를 직접 리턴하십시오.

    org.springframework.http.converter.json.MappingJacksonHttpMessageConverter를 메시지 변환기로 등록하고 메소드에서 객체를 직접 리턴하십시오.

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="webBindingInitializer">
        <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
      </property>
      <property name="messageConverters">
        <list>
          <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </list>
      </property>
    </bean>
    

    및 컨트롤러 :

    @RequestMapping(method=RequestMethod.GET, value="foo/bar")
    public @ResponseBody Object fooBar(){
        return myService.getActualObject();
    }
    

    org.springframework : spring-webmvc 의존성이 필요합니다.

  6. ==============================

    6.나는 response.setContentType (..)과는 별도로 할 수 있다고 생각하지 않는다.

    나는 response.setContentType (..)과는 별도로 할 수 있다고 생각하지 않는다.

  7. ==============================

    7.현실의 나의 버전. HTML 파일로드 및 브라우저로 스트리밍.

    현실의 나의 버전. HTML 파일로드 및 브라우저로 스트리밍.

    @Controller
    @RequestMapping("/")
    public class UIController {
    
        @RequestMapping(value="index", method=RequestMethod.GET, produces = "text/html")
        public @ResponseBody String GetBootupFile() throws IOException  {
            Resource resource = new ClassPathResource("MainPage.html");
            String fileContents = FileUtils.readFileToString(resource.getFile());
            return fileContents;
        }
    }
    
  8. from https://stackoverflow.com/questions/4471584/in-spring-mvc-how-can-i-set-the-mime-type-header-when-using-responsebody by cc-by-sa and MIT license