我创建了一个简单的Web服务(spring-web),用于验证传入的XML是否符合XSD规范,如果存在任何验证错误,则应将其返回给请求方。
下面的代码完成了它的任务...
@PostMapping(path = "/test", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> method2(@RequestBody Source request) throws IOException, JAXBException, SAXException {
final URL schemaUrl = resourceLoader.getResource("classpath:test.xsd").getURL();
final CumulatingErrorHandler errorHandler = new CumulatingErrorHandler();
final Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(schemaUrl);
final ValidationEventCollector validationEventCollector = new MyValidationEventCollector();
final Unmarshaller unmarshaller = JAXBContext
.newInstance(IncomingRequestModel.class)
.createUnmarshaller();
unmarshaller.setEventHandler(validationEventCollector);
unmarshaller.setSchema(schema);
final IncomingRequestModel requestModel = (IncomingRequestModel) unmarshaller.unmarshal(request);
if (validationEventCollector.hasEvents()) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
return new ResponseEntity<>(validationEventCollector.getEvents(), responseHeaders, HttpStatus.BAD_REQUEST);
}
/* do stuff */
}
...但是,由于某种奇怪的原因,它正在“累积”处理的请求之间的错误。在第一个请求中,返回了3个错误。同样,在第二个和第三个请求中也是如此。然而,在第四个请求中,UnmarshallingContext中的计数器达到零(从10开始倒数),并返回以下错误:
Errors limit exceeded. To receive all errors set com.sun.xml.internal.bind logger to FINEST level.
在第五个请求中,不会抛出任何验证错误!为了使其更明显 - 所有请求都完全相同。
为什么UnmarshallingContext有一个静态计数器来阻止第5次或更多次请求进行验证?我该如何解决这个问题?
我的构建配置:Spring boot 1.4.3.RELEASE,gradle依赖项:
dependencies {
compile('org.springframework.boot:spring-boot-starter-amqp')
compile('org.springframework.boot:spring-boot-starter-data-redis')
compile('org.springframework.boot:spring-boot-starter-jersey')
compile('org.springframework.boot:spring-boot-starter-web')
compile("com.fasterxml.jackson.core:jackson-databind")
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
compileOnly('org.projectlombok:lombok:1.16.12')
compile("net.sf.dozer:dozer:5.5.1")
compile("net.sf.dozer:dozer-spring:5.5.1")
compile("org.apache.commons:commons-lang3:3.5")
testCompile('org.springframework.boot:spring-boot-starter-test')
}