首页 > 解决方案 > Spring Boot 控制器建议 - 如何返回 XML 而不是 JSON?

问题描述

我有一个控制器建议类,但我似乎无法让它返回 XML,即使我使用了 @RequestMapping 注释。这是一个精简的示例。

@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(Exception.class)
    @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
    public PriceAvailabilityResponse handleControllerErrorXML(final Exception e){

        e.printStackTrace();
        System.out.println("Exception Handler functional");

        PriceAvailabilityResponse priceAvailabilityResponse = new PriceAvailabilityResponse();
        priceAvailabilityResponse.setStatusMessage("Server Error");
        priceAvailabilityResponse.setStatusCode(99);

        return priceAvailabilityResponse;
        }
}

请注意@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)休息控制器如何控制响应的形成方式。

PriceAvailabilityResponse这是上述代码块中可能出现的内容的示例。

    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @Getter
    @Setter
    public class PriceAvailabilityResponse {

        @JacksonXmlProperty(isAttribute = true, localName = "StatusCode")
        @JsonProperty(value = "StatusCode", required = false)
        private int statusCode = 0;

        @JacksonXmlProperty(isAttribute = true, localName = "StatusMessage")
        @JsonProperty(value = "StatusMessage", required = false)
        private String statusMessage;
    }

下面是一个抛出错误的示例休息控制器方法

@RequestMapping(value = "/error_test", produces = MediaType.APPLICATION_XML_VALUE)
public PriceAvailabilityResponse getPriceResponse() throws Exception{

    int x = 1/0;

    return null;
}

我已经为此代码编写了模型,以根据哪个端点访问微服务来返回 JSON 和 XML,这是绝对必要的。

不幸的是,当我找到/error_test路径时,我的响应总是以 JSON 格式出现。

在此处输入图像描述

如何强制响应为 XML?非常感谢您的宝贵时间。

标签: jsonxmlspringspring-bootcontroller-advice

解决方案


以下方法应该可以解决您的问题

@RestController
public class TestController {

@GetMapping(value = "/throw-exception", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity throwException(){
    throw new CustomException("My Exception");
}

}

从异常处理程序返回响应实体并用它指定媒体类型。

@ControllerAdvice
public class GlobalErrorHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(value = {CustomException.class})
protected ResponseEntity handleInvalidDataException(
        RuntimeException ex, WebRequest request) {

    PriceAvailabilityResponse priceAvailabilityResponse = new 
    PriceAvailabilityResponse();
    priceAvailabilityResponse.setStatusMessage("Server Error");
    priceAvailabilityResponse.setStatusCode(99);

    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
            .contentType(MediaType.APPLICATION_XML)
            .body(priceAvailabilityResponse);
}

}

如果没有,请包含 jackson-dataformat-xml 依赖项

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.9.8</version>
    </dependency>

推荐阅读