首页 > 解决方案 > Spring Boot Rest根据参数调用

问题描述

我对以下内容有疑问。我们想创建一些 Rest 调用。其余调用的参数之一是返回格式。所以参数 return_format 可以有 json 或 xml 的值。有没有一种聪明的方法来使用参数并使用能够产生正确输出格式的服务?

如果调用参数return_format == json 那么

@Produces({"application/json"}) 

如果调用参数 return_format == xml 那么

@Produces({"application/xml"})

标签: javaspringspring-bootrest

解决方案


您不需要像 return_format 这样的参数。这可以通过 Accept 标头来控制。

在控制器中,您可以添加两种格式:

@RequestMapping(value = "/employee", method = RequestMethod.GET,
                produces = { "application/json", "application/xml" })
public <yourResponse> get(@RequestHeader("Accept") String accept) {
    // Check if Accept is XML or JSON
}

推荐阅读