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 유형을 접근 할 수 있습니까?
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();
}
게임 :
첫째, <mvc:annotation-driven />
또는이 @EnableWebMvc
되어야하는 추가 응용 프로그램 설정에.
다음으로, 주석 의 생성 속성은 @RequestMapping
응답의 컨텐츠 유형을 지정하는 데 사용됩니다. 따라서 MediaType.APPLICATION_JSON_VALUE (또는 "application/json"
) 로 설정해야합니다 .
마지막으로, Java와 JSON은 어디에나 화 및 역화가 Spring에 의해 자동으로 처리되어야 Jackson을 추가해야합니다 (Jackson은 Spring에 의해 감지되고 내부에 MappingJacksonHttpMessageConverter
있음).
사용 ResponseEntity
대신에 ResponseBody
. 이렇게하면 응답 헤더에 액세스 할 수 있습니다. Spring 문서 에 따르면 :
은
HttpEntity
유사하다@RequestBody
와@ResponseBody
. 요청 및 응답 본문HttpEntity
(및 응답 특정 하위 클래스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);
}
@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();
}
}
나는 이것이 가능하다고 생각하지 않는다. 이에 대해 열려있는 Jira가있는 것입니다.
SPR-6702 : @ResponseBody에서 응답 Content-Type을 명시 적으로 설정
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
.
나는 당신이 할 수 있다고 생각하지 않습니다. response.setContentType(..)
나의 현실. 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;
}
}
'ProgramingTip' 카테고리의 다른 글
MySQL VARCHAR 길이 및 UTF-8 (0) | 2020.10.18 |
---|---|
테스트 파일을 JUnit으로 가져 오는 쉬운 방법 (0) | 2020.10.18 |
우편 번호로 도시 및 주 조회 Google Geocode API (0) | 2020.10.18 |
자바 펼쳐없이 HTML 양식에서 배열 게시 (0) | 2020.10.18 |
Eclipse 텍스트 커서가 변경되고 편집기가 다르게 작동합니다. (0) | 2020.10.18 |