Spring MVC 통합 jackson-dataformat-xml 문제
5922 단어 문 제 를 해결 하 다
HttpMessageNotWritableException
Could not write content
주:만약 당신 이 이 문 제 를 만 나 지 않 았 다 면 아래 의 해결 방법 2 를 직접 볼 수 있 습 니 다.
SpringBoot 통합 Spring MVC 에서 XML 형식 으로 출력 할 때 오류 가 발생 했 습 니 다.배경 오류 정 보 는 다음 과 같 습 니 다.
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Not implemented (through reference chain: org.github.abel533.springboot.model.Country[“id”]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Not implemented (through reference chain: org.github.abel533.springboot.model.Country[“id”])
페이지 알림 오 류 는 다음 과 같 습 니 다:
<html>
<body>
<h1>Whitelabel Error Pageh1>
<p>
This application has no explicit mapping for /error, so you are seeing this as a fallback.
p>
<div id="created">Sun Dec 27 10:35:49 CST 2015div>
<div>
There was an unexpected error (type=Internal Server Error, status=500).
div>
<div>
Could not write content: Not implemented (through reference chain: org.github.abel533.springboot.model.Country["id"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Not implemented (through reference chain: org.github.abel533.springboot.model.Country["id"])
div>
body>
html>
기본 적 인 상황 에서 오류 가 발생 한 이 유 는 하나 입 니 다.바로 아래 설정 을 사용 한 것 입 니 다.
spring.jackson.serialization.indent_output=true
이 설정 은 JSON 이 출력 을 포맷 하여 읽 기 편 하도록 합 니 다.하지만 이 설정 은 XML 에 부정적인 역할 을 합 니 다.
XML 을 출력 할 때 사용 합 니 다
DefaultXmlPrettyPrinter
.이 종 류 는 다음 방법 으로 XML 을 출력 할 때 사용 합 니 다.public void writeLeafElement(XMLStreamWriter2 sw,
String nsURI, String localName, int value)
throws XMLStreamException
Stax2WriterAdapter
클래스 의 아래 방법 으로 출력 합 니 다:public void writeRaw(String text, int offset, int len) throws XMLStreamException
{
// There is no clean way to implement this via Stax 1.0, alas...
throw new UnsupportedOperationException("Not implemented");
}
이 방법 이 실현 되 지 않 았 기 때문에,이것 은 위의 잘못된 발생 을 초래 하 였 다.
해결 방법
방법 1
아래 설정 을 사용 하기 때문에:
spring.jackson.serialization.indent_output=true
문제 가 발생 했 기 때문에 포맷 출력(기본 값
false
을 사용 하지 않 으 면 문제 가 되 지 않 습 니 다.방법 2
참고:https://github.com/FasterXML/jackson-dataformat-xml#maven-dependency
공식 github 에 다음 과 같이 썼 습 니 다.
Also: you usually also want to make sure that XML library in use is Woodstox since it is not only faster than Stax implementation JDK provides, but also works better and avoids some known issues like adding unnecessary namespace prefixes.
jackson-dataformat-xml
기본 값 으로 아래stax2-api
의존 도 를 사용 합 니 다. <dependency>
<groupId>org.codehaus.woodstoxgroupId>
<artifactId>stax2-apiartifactId>
<version>3.1.4version>
dependency>
stax2-api
의Stax2WriterAdapter
미 완성 실현 이 있 고 다른 문제 도 있다.또한Woodstox
가Stax
보다 빠 르 기 때문에 공식 추천 사용woodstox-core-asl
(Spring 공식 추천 도 이것):<dependency>
<groupId>org.codehaus.woodstoxgroupId>
<artifactId>woodstox-core-aslartifactId>
<version>4.4.1version>
dependency>
따라서 우 리 는 위의
woodstox-core-asl
의존 만 추가 하면 문 제 를 해결 할 수 있다.