有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Spring RestTemplate处理json类型请求和xml类型请求

有时我会以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。发布版本


共 (1) 个答案

  1. # 1 楼答案

    正如jbarrueta在评论中所说,您需要在Controller中声明两个方法,例如

    getCustomerJsongetCustomerXML

    第一种方法的映射为:

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

    第二种方法的映射是:

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