【问题标题】:How to handle json type request and xml type request using Spring RestTemplate如何使用 Spring RestTemplate 处理 json 类型请求和 xml 类型请求
【发布时间】:2015-04-28 06:58:16
【问题描述】:

有时我会收到 json(来自 rest 客户端)格式的请求,有时我会收到 xml(来自使用 jsp 视图的表单)格式的请求。当我编写如下所示的控制器类时,它将不允许请求 xml(来自使用 jsp 视图的表单)。

这是我的问题。控制器类应该允许这两种类型的请求。

@RequestMapping(value = "/home", method = RequestMethod.POST)
    public String getCustomer(@RequestBody HomeRequest homeRequestequest,
            HttpServletRequest request) {

        String response = homeService.getCustomerResponse(homeRequestequest, request);
         return response;
        } 

请帮助解决这个问题。我使用的是 3.2.4.RELEASE 版本。

【问题讨论】:

  • 控制器@RestController@Controller上的annotation是什么?
  • 我正在使用@controller
  • “不允许”是什么意思?
  • 请求还是响应?!!! getCustomer() 应该返回 xml/json 响应或请求是 xml/json !!!进行适当的描述。
  • 如果请求必须接受来自表单和 Json 主体的 POST,您的 Controller 方法必须接受 application/x-www-form-urlencodedapplication/json。您可能想尝试 RequestMapping 注释中的consumes,但最终我认为您应该声明两个共享相同业务逻辑的方法。

标签: java json spring resttemplate


【解决方案1】:

正如jbarrueta在cmets中所说,你需要在Controller中声明2个方法,例如

getCustomerJsongetCustomerXML

第一种方法的映射是:

@RequestMapping(value = "/home", method = RequestMethod.POST, consumes = "application/json")

第二种方法的映射是:

@RequestMapping(value = "/home", method = RequestMethod.POST, consumes = "application/xml")

【讨论】:

  • 我们应该写2个方法...?除了写两种方法,我还有其他解决方案
猜你喜欢
  • 2014-03-16
  • 1970-01-01
  • 2019-06-23
  • 2016-05-29
  • 2022-09-23
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多